สำหรับสิ่งนี้ ให้ใช้ $elemMatch ซึ่งใช้ในการสืบค้นวัตถุที่ซ้อนกัน ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo444.insertOne(
... {
... "Information": [{
... id:1,
... Name:"Chris"
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e78ea87bbc41e36cc3caebf")
}
> db.demo444.insertOne(
... {
... "Information": [{
... id:2,
... Name:"David"
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e78ea87bbc41e36cc3caec0")
}
> db.demo444.insertOne(
... {
... "Information": [{
... id:3,
... Name:"Bob"
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e78ea88bbc41e36cc3caec1")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo444.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caebf"), "Information" : [ { "id" : 1, "Name" : "Chris" } ] }
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caec0"), "Information" : [ { "id" : 2, "Name" : "David" } ] }
{ "_id" : ObjectId("5e78ea88bbc41e36cc3caec1"), "Information" : [ { "id" : 3, "Name" : "Bob" } ] } ต่อไปนี้เป็นแบบสอบถามเพื่อปรับปรุงการสืบค้นด้วยดัชนี multikey ในอาร์เรย์ -
> db.demo444.find({
... "Information":{
... $elemMatch:{
... id:2,
... Name:"David"
... }
... }
... }) สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caec0"), "Information" : [ { "id" : 2, "Name" : "David" } ] }