【发布时间】: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