【问题标题】:How to replace root with an array field during MongoDB aggregation pipeline?如何在 MongoDB 聚合管道期间用数组字段替换 root?
【发布时间】:2020-10-24 16:49:33
【问题描述】:

假设我有一个 users 集合,其中一个 roleIds 字段包含一个 Role 引用数组。

db.users.aggregate([
  {$match:{ _id: ObjectId('5f9453b4484d206714c02a2f') }}, 
  {$project:{ roleIds: 1, _id: 0 }}, 
  {$unwind: "$roleIds"}, 
  {$lookup:{ from: "roles", localField: "roleIds", foreignField: "_id", as: "roles"}}, // <= STEP 4
  {$replaceRoot: "$roles"}
])

在第 4 步之后,我有这样的东西:

{ 
  "roles" : [ 
    { "_id" : ObjectId("xxxx"), "name" : "role1" },
    { "_id" : ObjectId("xxxx"), "name" : "role2" },
  ]
}

我怎样才能把它变成这样:

[ 
  { "_id" : ObjectId("xxxx"), "name" : "role1" },
  { "_id" : ObjectId("xxxx"), "name" : "role2" },
]

replaceRoot 阶段似乎仅在角色字段是文档而不是数组时才起作用,在这种情况下会引发错误。

【问题讨论】:

  • 你能提供一些示例文件吗?
  • { $unwind: "$roles" }$replaceRoot 之前解构数组。

标签: mongodb aggregation-framework


【解决方案1】:

这行得通:

db.users.aggregate([
  {$match:{ _id: ObjectId('5f9453b4484d206714c02a2f') }}, 
  {$project:{ roleIds: 1, _id: 0 }}, 
  {$unwind: "$roleIds"}, 
  {$lookup:{ from: "roles", localField: "roleIds", foreignField: "_id", as: "roles"}},
  {$unwind: "$roles"},
  {$replaceRoot: { newRoot: "$roles" }}
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 2020-12-12
    • 2019-11-29
    相关资源
    最近更新 更多