สำหรับกรณีนี้ ให้ใช้ $push ร่วมกับ update มาสร้างคอลเล็กชันกันเถอะ
> db.demo573.insertOne(
{
'_id' :101,
'SearchInformation' : [
{
'Site' : 'Facebook.com',
'NumberOfHits' : 100
},
{
'Site' : 'Twitter.com',
'NumberOfHits' : 300
}
]
}
);
{ "acknowledged" : true, "insertedId" : 101 }
แสดงเอกสารทั้งหมดด้วยเมธอด find()
> db.demo573.find();
ผลลัพธ์ที่ได้
{ "_id" : 101, "SearchInformation" : [ { "Site" : "Facebook.com", "NumberOfHits" : 100 }, { "Site" : "Twitter.com", "NumberOfHits" : 300 } ] }
คำสั่งสืบค้นอาร์เรย์เอกสารฝังตัวและเพิ่ม Google.com (ถ้ายังไม่มี)
> db.demo573.update({
_id: 101,
"SearchInformation.Site": {
$nin: ["Google.com"]
}
}, {
$push: {
"SearchInformation": {
'Site' : 'Google.com',
'NumberOfHits' : 10000
}
}
});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
แสดงเอกสารทั้งหมดหลังเพิ่ม
> db.demo573.find().pretty();
ผลลัพธ์ที่ได้
{ "_id" : 101, "SearchInformation" : [ { "Site" : "Facebook.com", "NumberOfHits" : 100 }, { "Site" : "Twitter.com", "NumberOfHits" : 300 }, { "Site" : "Google.com", "NumberOfHits" : 10000 } ] }