Để tìm tài liệu nào chứa một chuỗi cụ thể, hãy sử dụng $ regex cùng với find (). Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.demo597.insertOne({"Name":"John Doe"});{
"acknowledged" : true, "insertedId" : ObjectId("5e947ae3f5f1e70e134e2690")
}
> db.demo597.insertOne({"Name":"John Smith"});{
"acknowledged" : true, "insertedId" : ObjectId("5e947ae8f5f1e70e134e2691")
}
> db.demo597.insertOne({"Name":"Chris Brown"});{
"acknowledged" : true, "insertedId" : ObjectId("5e947aeff5f1e70e134e2692")
}
> db.demo597.insertOne({"Name":"Adam Smith"});{
"acknowledged" : true, "insertedId" : ObjectId("5e947afff5f1e70e134e2693")
} 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.demo597.find();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e947ae3f5f1e70e134e2690"), "Name" : "John Doe" }
{ "_id" : ObjectId("5e947ae8f5f1e70e134e2691"), "Name" : "John Smith" }
{ "_id" : ObjectId("5e947aeff5f1e70e134e2692"), "Name" : "Chris Brown" }
{ "_id" : ObjectId("5e947afff5f1e70e134e2693"), "Name" : "Adam Smith" } Sau đây là truy vấn để tìm tài liệu MongoDB nào chứa một chuỗi cụ thể -
> db.demo597.find({Name:{$regex:/smith/i}} ); Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e947ae8f5f1e70e134e2691"), "Name" : "John Smith" }
{ "_id" : ObjectId("5e947afff5f1e70e134e2693"), "Name" : "Adam Smith" }