在mongo中应用$ filter后,投影特定的嵌套数组属性

时间:2018-08-07 18:50:18

标签: mongodb mongodb-query

我要查询的集合包含具有以下结构的文档-

{
  "_id": 1,
  "topA": "topAValue",
  "topB": "topBValue",
  "topC": "topCValue",
  "nestedDocArray": [
    {
      "attr1": "a",
      "attr2": "b",
      "attr3": "c"
    },
    {
      "attr1": "a5",
      "attr2": "b5",
      "attr3": "c5"
    },
    {
      "attr1": "a1000",
      "attr2": "b1000",
      "attr3": "c1000"
    }
  ]
}

我正在尝试使用“ _id”:1查询此文档,要求仅投影某些属性。除此之外,要求仅获取符合条件“ attr1”:“ a5”的nestedDocArray。

我尝试过的查询如下-

db.testCollection.aggregate(
[
  {
    "$match": {
      "_id": 1
    }
  },
  {
    "$project": {
      "topA": 1,
      "nestedDocArray": {
        "$filter": {
          "input": "$nestedDocArray",
          "as": "nestedDocArray",
          "cond": {
            "$eq": [
              "$$nestedDocArray.attr1",
              "a5"
            ]
          }
        }
      }
    }
  }
]
);

此查询的响应如下所示-

{
  "_id": 1,
  "topA": "topAValue",
  "nestedDocArray": [
    {
      "attr1": "a5",
      "attr2": "b5",
      "attr3": "c5"
    }
  ]
}

很好。这已经成功地投影了属性topA和nestedDocArray。 我进一步想只投影nestedDocArray.attr2。 我正在寻找的输出如下所示。

{
  "_id": 1,
  "topA": "topAValue",
  "nestedDocArray": [
    {
      "attr2": "b5"
    }
  ]
}

如何修改查询以实现相同的目的?

1 个答案:

答案 0 :(得分:1)

您可以将$map$filter结合使用来重塑数据:

db.testCollection.aggregate([
    {
        $match: { _id: 1 }
    },
    {
        $project: {
            topA: 1,
            nestedDocArray: {
                $map: {
                    input: {
                        $filter: {
                            input: "$nestedDocArray",
                            as: "nestedDocArray",
                            cond: {
                                $eq: [ "$$nestedDocArray.attr1", "a5" ]
                            }
                        }
                    },
                    as: "item",
                    in: {
                        attr2: "$$item.attr2"
                    }
                }
            }
        }
    }
])
相关问题