重命名($ project)数组中的字段 - MongoDB

时间:2018-03-09 11:57:24

标签: mongodb mongodb-query aggregation-framework

我有一个如下文档,

{
    "_id" : "59ba903dacea50d0d7d47168",
    "sections" : [ 
        {
            "_id" : "59d9dd7947ce651544c5d4c1",
            "sectionName" : "Section 1"
        }, 
        {
            "_id" : "59d9dd8147ce651544c5d4c2",
            "sectionName" : "Section 2"
        }, 
        {
            "_id" : "59d9dd9747ce651544c5d4c3",
            "sectionName" : "Section 3"
        }
    ]
}

我使用投影将字段_id重命名为id,将sectionName重命名为使用查询

的名称
db.getCollection('tmp').aggregate([
{$project:{"sections.id":"$sections._id", "sections.name":"$sections.sectionName"}}
])

所需的输出是:

{
    "_id": "59ba903dacea50d0d7d47168",
    "sections": [
        {"id": "59d9dd7947ce651544c5d4c1", "name": "Section 1"}, 
        {"id": "59d9dd8147ce651544c5d4c2", "name": "Section 2"}, 
        {"id": "59d9dd9747ce651544c5d4c3", "name": "Section 3"}
    ]
};

但它似乎不起作用,我做错了什么?

请注意,我不是要像in this question那样更新此文档,我想以所需的格式投放文档。

1 个答案:

答案 0 :(得分:1)

如果我理解得很好,应该通过$map运算符完成,如下所示:

db.getCollection('section').aggregate([
    {
        $project: {
           sections: {
               $map: {
                   "input": "$sections",
                   as: "sec",
                   in: {
                       "my_id": "$$sec._id",
                       "new_section_name": "$$sec.sectionName"
                   }
               }
           }
        }
    }
])

输出类似于吼叫:

{
  "waitedMS": NumberLong("0"),
  "result": [
    {
      "_id": "59ba903dacea50d0d7d47168",
      "sections": [
        {
          "my_id": "59d9dd7947ce651544c5d4c1",
          "new_section_name": "Section 1"
        },
        {
          "my_id": "59d9dd8147ce651544c5d4c2",
          "new_section_name": "Section 2"
        },
        {
          "my_id": "59d9dd9747ce651544c5d4c3",
          "new_section_name": "Section 3"
        }
      ]
    }
  ],
  "ok": 1
}