Đối với giá trị tìm kiếm, hãy sử dụng $ match trong MongoDB. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.demo648.insertOne(
... {
... StudentInformation:
... [
... {
... Name:"John",
... CountryName:"US"
... },
... {
... Name:"David",
... CountryName:"AUS"
... },
... {
... Name:"Chris",
... CountryName:"US"
... },
... {
... Name:"Robert",
... CountryName:"UK"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c8b286c954c74be91e6f5")
} 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.demo648.find();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e9c8b286c954c74be91e6f5"), "StudentInformation" : [
{ "Name" : "John", "CountryName" : "US" },
{ "Name" : "David", "CountryName" : "AUS" },
{ "Name" : "Chris", "CountryName" : "US" },
{ "Name" : "Robert", "CountryName" : "UK" }
] } Sau đây là truy vấn để tìm kiếm giá trị trong MongoDB -
> db.demo648.aggregate([
... { $unwind: "$StudentInformation" },
... { $match: { "StudentInformation.CountryName": "US" } },
... { $project: {_id: 0}}
... ]) Điều này sẽ tạo ra kết quả sau -
{ "StudentInformation" : { "Name" : "John", "CountryName" : "US" } }
{ "StudentInformation" : { "Name" : "Chris", "CountryName" : "US" } }