เพื่อจับคู่ทุกค่าใน MongoDB ให้ใช้ $match ร่วมกับ $and ใน Aggregation มาสร้างคอลเล็กชันกันเถอะ
> db.demo574.insertOne(
{
"details1": {
"details2": {
"dueDate": new ISODate("2020-01-10"),
"Name": "Chris",
"UserInformation": {
"Name": "John",
"Marks": 78
},
CountryName:"US"
},
id:101
}
}
);
{ "acknowledged" : true, "insertedId" : ObjectId("5e9167f3581e9acd78b427f6") }
แสดงเอกสารทั้งหมดด้วยเมธอด find()
> db.demo574.find();
ผลลัพธ์ที่ได้
{ "_id" : ObjectId("5e9167f3581e9acd78b427f6"), "details1" : { "details2" : { "dueDate" : ISODate("2020-01-10T00:00:00Z"), "Name" : "Chris", "UserInformation" : { "Name" : "John", "Marks" : 78 }, "CountryName" : "US" }, "id" : 101 } }
คำสั่ง Aggregation ทำงานกับ $match และ $and
> db.demo574.aggregate({
$match: {
$and: [
{"details1.id": 101},
{"details1.details2.UserInformation.Name": 'John'},
{"details1.details2.Name": 'Chris'}
]
}
});
ผลลัพธ์ที่ได้
{ "_id" : ObjectId("5e9167f3581e9acd78b427f6"), "details1" : { "details2" : { "dueDate" : ISODate("2020-01-10T00:00:00Z"), "Name" : "Chris", "UserInformation" : { "Name" : "John", "Marks" : 78 }, "CountryName" : "US" }, "id" : 101 } }