重命名($project)数组中的字段 - MongoDB [英] Rename ($project) a field from an array - MongoDB

查看:60
本文介绍了重命名($project)数组中的字段 - MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像下面这样的文档,

I have a document like the following,

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

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

I am using projection to rename the fields _id to id and sectionName to name using the query

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"}
    ]
};

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

But it doesn't seem to work, what am I doing wrong?

请注意,我不会像 在这个问题中,我想以所需的格式投影文档.

Please note that I am not trying to update this document like in this question, I want to project the document in the desired format.

推荐答案

如果我理解得很好,应该通过 $map 操作符,像这样:

If i did understand it well, it should be done via $map operator, like this:

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
}

这篇关于重命名($project)数组中的字段 - MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆