[英]In MongoDB aggregation pipeline, how to project a returned field into an array of that value
[英]How to replace root with an array field during MongoDB aggregation pipeline?
假设我有一个users
collections,其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
阶段似乎只有在角色字段是文档而不是数组时才有效,在这种情况下它会抛出错误。
这有效:
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" }}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.