【问题标题】:MongoDB $project embedded document to root level with other fields in another documentMongoDB $project 嵌入文档到根级别以及另一个文档中的其他字段
【发布时间】:2020-04-20 02:49:33
【问题描述】:

我有这个结构

 {
        "_id": "5e7229c248797243544a15b6",
        "itinerary": [
            {
                "_id": "5e96f905c694d020bc99c2e4"
            },
            {
                "_id": "5e7230360bab9640f82a0e79"
            }
        ]
    },

并且需要这种方式的转换文件

    { "_id": "5e7229c248797243544a15b6"},
    { "_id": "5e96f905c694d020bc99c2e4"},
    { "_id": "5e7230360bab9640f82a0e79"}

感谢您的帮助团队。 :)

【问题讨论】:

    标签: mongodb aggregate


    【解决方案1】:

    试试这个:

    db.collection.aggregate([
      {
        $project: {
          data: {
            $concatArrays: [
              [
                { _id: "$_id" }
              ],
              {
                $map: {
                  input: "$itinerary",
                  in: "$$this"
                }
              }
            ]
          }
        }
      },
      {
        $unwind: "$data"
      },
      {
        $replaceRoot: {
          newRoot: "$data"
        }
      }
    ])
    

    MongoPlayground

    【讨论】:

    • ¿我可以解构行程吗?
    • @DanielLopez 你需要做什么?
    • 我需要将行程 _id 保留在根级别,以便稍后将它们分组。
    • @DanielLopez 请发布您的加速结果,我可以更改管道。如果在$project 阶段之前添加{$undind : "$itinerary"},则可以将其拼合为单独的文档。
    • 你能看到我的查询吗
    猜你喜欢
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多