Computer >> Máy Tính >  >> Lập trình >> MongoDB

MongoDB Regex Tìm kiếm trên Giá trị Số nguyên?

Để thực hiện tìm kiếm Regex trên giá trị số nguyên, bạn cần sử dụng toán tử $ where. Cú pháp như sau:

db.yourCollectionName.find({ $where:
"/^yourIntegerPatternValue.*/.test(this.yourFieldName)" });

Để hiểu khái niệm trên, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với tài liệu như sau:

> db.regExpOnIntegerDemo.insertOne({"StudentId":2341234});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c70370c75eb1743ddddce21")
}
> db.regExpOnIntegerDemo.insertOne({"StudentId":123234});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c70371175eb1743ddddce22")
}
> db.regExpOnIntegerDemo.insertOne({"StudentId":9871234});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c70371875eb1743ddddce23")
}
> db.regExpOnIntegerDemo.insertOne({"StudentId":2345612});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c70372275eb1743ddddce24")
}
> db.regExpOnIntegerDemo.insertOne({"StudentId":1239812345});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c70372975eb1743ddddce25")
}

Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau:

> db.regExpOnIntegerDemo.find().pretty();

Sau đây là kết quả:

{ "_id" : ObjectId("5c70370c75eb1743ddddce21"), "StudentId" : 2341234 }
{ "_id" : ObjectId("5c70371175eb1743ddddce22"), "StudentId" : 123234 }
{ "_id" : ObjectId("5c70371875eb1743ddddce23"), "StudentId" : 9871234 }
{ "_id" : ObjectId("5c70372275eb1743ddddce24"), "StudentId" : 2345612 }
{ "_id" : ObjectId("5c70372975eb1743ddddce25"), "StudentId" : 1239812345 }

Đây là truy vấn để thực hiện tìm kiếm Regex trên giá trị số nguyên:

> db.regExpOnIntegerDemo.find({ $where: "/^123.*/.test(this.StudentId)" });

Sau đây là kết quả:

{ "_id" : ObjectId("5c70371175eb1743ddddce22"), "StudentId" : 123234 }
{ "_id" : ObjectId("5c70372975eb1743ddddce25"), "StudentId" : 1239812345 }