查找MongoDB文档,其中数组中的所有对象都具有特定值?
让我们创建一个包含文档的集合-
> 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" } ] }