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

Tìm tài liệu có chứa một giá trị cụ thể trong MongoDB bằng Biểu thức chính quy?


Để tìm tài liệu có chứa một giá trị cụ thể với Biểu thức chính quy, hãy sử dụng MongoDB $ 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.demo469.insertOne({"StudentName":"John Doe"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e80532fb0f3fa88e227906b")
}
> db.demo469.insertOne({"StudentName":"Chris Brown"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e80533ab0f3fa88e227906c")
}
> db.demo469.insertOne({"StudentName":"John Smith"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e805341b0f3fa88e227906d")
}
> db.demo469.insertOne({"StudentName":"Jace Doe"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e805347b0f3fa88e227906e")
}
> db.demo469.insertOne({"StudentName":"David Miller"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e80534eb0f3fa88e227906f")
}

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

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

{ "_id" : ObjectId("5e80532fb0f3fa88e227906b"), "StudentName" : "John Doe" }
{ "_id" : ObjectId("5e80533ab0f3fa88e227906c"), "StudentName" : "Chris Brown" }
{ "_id" : ObjectId("5e805341b0f3fa88e227906d"), "StudentName" : "John Smith" }
{ "_id" : ObjectId("5e805347b0f3fa88e227906e"), "StudentName" : "Jace Doe" }
{ "_id" : ObjectId("5e80534eb0f3fa88e227906f"), "StudentName" : "David Miller" }

Sau đây là truy vấn để tìm tài liệu chứa một giá trị cụ thể trong MongoDB -

> db.demo469.find({'StudentName': {'$regex':'john', '$options':'i'}});

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

{ "_id" : ObjectId("5e80532fb0f3fa88e227906b"), "StudentName" : "John Doe" }
{ "_id" : ObjectId("5e805341b0f3fa88e227906d"), "StudentName" : "John Smith" }