如何过滤嵌套/下级子文档

时间:2018-08-14 03:29:52

标签: mongodb mongoose

如果我有这样的结果,请说:

    {
        "_id" : ObjectId("5b722d06c23b5f2bd0329a41"),
        "name" : "test",
        "item" : {
            "_id" : ObjectId("5b722d07c23b5f2bd0329a53"),
            "display_name" : "",
            "image" : "http://via.placeholder.com/700x500/ffffff/000000/?text=No%20Image&",
            "is_private" : true,
            "details" : [
                {
                    "is_private" : false,
                    "type" : "text",
                    "_id" : ObjectId("5b722d06c23b5f2bd0329a44"),
                    "title" : "Name",
                    "content" : "",
                    "order" : 0
                },
                {
                    "is_private" : false,
                    "type" : "text",
                    "_id" : ObjectId("5b722d06c23b5f2bd0329a43"),
                    "title" : "Price",
                    "content" : "",
                    "order" : 1
                },
                {
                    "is_private" : false,
                    "type" : "text",
                    "_id" : ObjectId("5b722d06c23b5f2bd0329a42"),
                    "title" : "Company",
                    "content" : "",
                    "order" : 2
                }
            ],
            "tags" : [ ],
            "__v" : 0
        }
    }

并且我想按item.details.is_private进行过滤,该怎么办?我想返回item的所有属性,但如果它是item.details.is_private则过滤掉任何true

我目前将其投影为:

{
    "$project": {
        name: 1,
        item: 1
    }
}

但不确定如何在此设置中实现$filter

1 个答案:

答案 0 :(得分:1)

您可以尝试将$addsFields$filter聚合一起使用

db.collection.aggregate([
  { "$addFields": {
    "item.details": {
      "$filter": {
        "input": "$item.details",
        "as": "detail",
        "cond": {
          "$eq": [ "$$detail.is_private", true ]
        }
      }
    }
  }}
])