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

MongoDB:Tìm tên tương tự với đầu vào Biểu thức chính quy?


Gửi tên bằng $ regex trong MongoDB để tìm tên tương tự với đầu vào. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -

> db.demo514.insertOne({"Information":{"FullName":"John Doe"}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e885116987b6e0e9d18f58c")
}
> db.demo514.insertOne({"Information":{"FullName":"John Smith"}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e88515e987b6e0e9d18f58d")
}
> db.demo514.insertOne({"Information":{"FullName":"john doe"}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e885169987b6e0e9d18f58e")
}
> db.demo514.insertOne({"Information":{"FullName":"Chris Brown"}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e88516f987b6e0e9d18f58f")
}

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

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

{ "_id" : ObjectId("5e885116987b6e0e9d18f58c"), "Information" : { "FullName" : "John Doe" } }
{ "_id" : ObjectId("5e88515e987b6e0e9d18f58d"), "Information" : { "FullName" : "John Smith" } }
{ "_id" : ObjectId("5e885169987b6e0e9d18f58e"), "Information" : { "FullName" : "john doe" } }
{ "_id" : ObjectId("5e88516f987b6e0e9d18f58f"), "Information" : { "FullName" : "Chris Brown" } }

Sau đây là truy vấn để tìm tên tương tự với đầu vào -

> db.demo514.find({'Information.FullName': {$regex: "John Doe", $options: 'i'}});

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

{ "_id" : ObjectId("5e885116987b6e0e9d18f58c"), "Information" : { "FullName" : "John Doe" } }
{ "_id" : ObjectId("5e885169987b6e0e9d18f58e"), "Information" : { "FullName" : "john doe" } }