查找其中数组中所有对象具有特定值的 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"
      }
   ]
}

更新时间: 30-3-2020

467 次浏览

开启你的 职业

完成课程以获得认证

开始
广告