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

Truy vấn MongoDB với tiêu chí độ dài?

Để truy vấn MongoDB với tiêu chí độ dài, bạn có thể sử dụng regex. Sau đây là cú pháp

db.yourCollectionName.find({ ‘yourFieldName’: { $regex: /^.{yourLengthValue1,yourLengthValue2}$/ } });

Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu. Sau đây là truy vấn

> db.queryLengthDemo.insertOne({"StudentFullName":"John Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a01ae353decbc2fc927c0")
}
> db.queryLengthDemo.insertOne({"StudentFullName":"John Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a01b4353decbc2fc927c1")
}
> db.queryLengthDemo.insertOne({"StudentFullName":"David Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a01c2353decbc2fc927c2")
}
> db.queryLengthDemo.insertOne({"StudentFullName":"Robert Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a01e2353decbc2fc927c3")
}
> db.queryLengthDemo.insertOne({"StudentFullName":"Chris Williams"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a01f1353decbc2fc927c4")
}

Sau đây là truy vấn để 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 ()

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

Điều này sẽ tạo ra kết quả sau

{
   "_id" : ObjectId("5c9a01ae353decbc2fc927c0"),
   "StudentFullName" : "John Smith"
}
{
   "_id" : ObjectId("5c9a01b4353decbc2fc927c1"),
   "StudentFullName" : "John Doe"
}
{
   "_id" : ObjectId("5c9a01c2353decbc2fc927c2"),
   "StudentFullName" : "David Miller"
}
{
   "_id" : ObjectId("5c9a01e2353decbc2fc927c3"),
   "StudentFullName" : "Robert Taylor"
}
{
   "_id" : ObjectId("5c9a01f1353decbc2fc927c4"),
   "StudentFullName" : "Chris Williams"
}

Sau đây là truy vấn trong MongoDB với tiêu chí độ dài

> db.queryLengthDemo.find({ StudentFullName: { $regex: /^.{9,12}$/ } }).pretty();

Điều này sẽ tạo ra kết quả sau

{
   "_id" : ObjectId("5c9a01ae353decbc2fc927c0"),
   "StudentFullName" : "John Smith"
}
{
   "_id" : ObjectId("5c9a01c2353decbc2fc927c2"),
   "StudentFullName" : "David Miller"
}