MongoDB filter nested array

北城以北 提交于 2021-01-29 12:20:55

问题


I have a collection that looks something like:

[
  {
    "_id": 1,
    "title": "dummy title",
    "settings": [
      {
        "type": "light",
        "status": "enabled"
      },
      {
        "type": "flare",
        "status": "disabled"
      },
      {
        "type": "toolbar",
        "status": "enabled"
      }
    ]
  }
]

I wanna fetch it by Id but only with the "enabled" settings and not sure how the aggregation pipeline should look like.

I supposed to create the query using mongoTemplate in Java / Kotlin but even just the mongo query would be enough.


回答1:


You can do it with a $filter

db.collection.aggregate([
  {
    $project: {
      _id: 1,
      title: 1,
      settings: {
        $filter: {
          input: "$settings",
          as: "item",
          cond: {
            $eq: [
              "$$item.status",
              "enabled"
            ]
          }
        }
      }
    }
  }
])

try it here




回答2:


//working code from MongoDB shell/CLI version 4.26(on windows 10 machine/OS)
> db.titles.find().pretty();
{
        "_id" : 1,
        "title" : "dummy title",
        "settings" : [
                {
                        "type" : "light",
                        "status" : "enabled"
                },
                {
                        "type" : "flare",
                        "status" : "disabled"
                },
                {
                        "type" : "toolbar",
                        "status" : "enabled"
                }
        ]
}
> db.titles.aggregate([
... {$unwind:"$settings"},
... {$match:{"settings.status":"enabled"}}
... ]);
{ "_id" : 1, "title" : "dummy title", "settings" : { "type" : "light", "status" : "enabled" } }
{ "_id" : 1, "title" : "dummy title", "settings" : { "type" : "toolbar", "status" : "enabled" } }
> print("MongoDB: ",db.version());
MongoDB:  4.2.6
>


来源:https://stackoverflow.com/questions/64306166/mongodb-filter-nested-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!