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

Biểu thức chính quy MongoDB để tìm nạp bản ghi có tên cụ thể “John”, thay vì “john”

Để tìm kiếm một từ cụ thể, hãy sử dụng / searchWord / với regex. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -

> db.demo221.insertOne({"Details":{"StudentName":"Chris","StudentAge":21}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ee15d03d395bdc213472b")
}
> db.demo221.insertOne({"Details":{"StudentName":"John","StudentAge":20}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ee16503d395bdc213472c")
}
> db.demo221.insertOne({"Details":{"StudentName":"Bob","StudentAge":22}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ee16b03d395bdc213472d")
}
> db.demo221.insertOne({"Details":{"StudentName":"john","StudentAge":24}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ee17303d395bdc213472e")
}

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.demo221.find();

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

{ "_id" : ObjectId("5e3ee15d03d395bdc213472b"), "Details" : { "StudentName" : "Chris", "StudentAge" : 21 } }
{ "_id" : ObjectId("5e3ee16503d395bdc213472c"), "Details" : { "StudentName" : "John", "StudentAge" : 20 } }
{ "_id" : ObjectId("5e3ee16b03d395bdc213472d"), "Details" : { "StudentName" : "Bob", "StudentAge" : 22 } }
{ "_id" : ObjectId("5e3ee17303d395bdc213472e"), "Details" : { "StudentName" : "john", "StudentAge" : 24 } }

Sau đây là truy vấn để tìm nạp một bản ghi cụ thể có tên “John” -

> db.demo221.find({"Details.StudentName":/John/});

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

{ "_id" : ObjectId("5e3ee16503d395bdc213472c"), "Details" : { "StudentName" : "John", "StudentAge" : 20 } }