ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo74.insertOne( ... { ... StudentName: "Chris", ... StudentDetails: [{ ... "Subject": "MongoDB", ... "isRegular": "Active" ... },{ ... "Subject": "MongoDB", ... "isRegular": "InActive" ... },{ ... "Subject": "MongoDB", ... "isRegular": "InActive" ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e29c6b671bf0181ecc4226f") } > db.demo74.insertOne({ ... name: "document2", ... data: [{ ... "Subject": "MongoDB", ... "isRegular": "Active" ... },{ ... "Subject": "MongoDB", ... "isRegular": "Active" ... },{ ... "Subject": "MongoDB", ... "isRegular": "Active" ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e29c6b771bf0181ecc42270") }
แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo74.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e29c6b671bf0181ecc4226f"), "StudentName" : "Chris", "StudentDetails" : [ { "Subject" : "MongoDB", "isRegular" : "Active" }, { "Subject" : "MongoDB", "isRegular" : "InActive" }, { "Subject" : "MongoDB", "isRegular" : "InActive" } ] } { "_id" : ObjectId("5e29c6b771bf0181ecc42270"), "name" : "document2", "data" : [ { "Subject" : "MongoDB", "isRegular" : "Active" }, { "Subject" : "MongoDB", "isRegular" : "Active" }, { "Subject" : "MongoDB", "isRegular" : "Active" } ] }
ต่อไปนี้เป็นแบบสอบถามเพื่อค้นหาเอกสารที่วัตถุทั้งหมดในอาร์เรย์มีค่าเฉพาะ -
> db.demo74.find({ " StudentDetails": { "$not": { "$elemMatch": { "isRegular": { $ne: "Active" } } } }, "StudentDetails.isRegular": "Active" }).pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e29c6b671bf0181ecc4226f"), "StudentName" : "Chris", "StudentDetails" : [ { "Subject" : "MongoDB", "isRegular" : "Active" }, { "Subject" : "MongoDB", "isRegular" : "InActive" }, { "Subject" : "MongoDB", "isRegular" : "InActive" } ] }