我正在尝试使用聚合框架创建查询,但我无法获得想要的结果。 我有一个经销商集合,每个经销商都有一个客户列表,每个客户都有一个成员列表,结构如下:
[
{
"userID" : "xxx",
"userType" : "RESELLER",
"clients" : [
{
"userID" : "xxx",
"userType" : "CLIENT",
"members" : [
{
"userID" : "xxx",
"userType" : "MEMBER"
},
{
"userID" : "xxx",
"userType" : "MEMBER"
}
]
},
{
"userID" : "xxx",
"userType" : "CLIENT",
"members" : [
{
"userID" : "xxx",
"userType" : "MEMBER"
},
{
"userID" : "xxx",
"userType" : "MEMBER"
}
]
}
]
},
{
"userID" : "xxx",
"userType" : "RESELLER",
"clients" : [
{
"userID" : "xxx",
"userType" : "CLIENT",
"members" : [
{
"userID" : "xxx",
"userType" : "MEMBER"
},
{
"userID" : "xxx",
"userType" : "MEMBER"
}
]
},
{
"userID" : "xxx",
"userType" : "CLIENT",
"members" : [
{
"userID" : "xxx",
"userType" : "MEMBER"
},
{
"userID" : "xxx",
"userType" : "MEMBER"
}
]
}
]
}
]
我想要得到的结果是:
[
{
"userID" : "xxx",
"userType" : "RESELLER"
},
{
"userID" : "xxx",
"userType" : "RESELLER"
},
{
"userID" : "xxx",
"userType" : "CLIENT"
},
{
"userID" : "xxx",
"userType" : "CLIENT"
},
{
"userID" : "xxx",
"userType" : "CLIENT"
},
{
"userID" : "xxx",
"userType" : "CLIENT"
},
{
"userID" : "xxx",
"userType" : "MEMBER"
},
{
"userID" : "xxx",
"userType" : "MEMBER"
},
{
"userID" : "xxx",
"userType" : "MEMBER"
},
{
"userID" : "xxx",
"userType" : "MEMBER"
},
{
"userID" : "xxx",
"userType" : "MEMBER"
}
]
我做了很多次尝试,但我没有得到这个结果。 我所做的最接近的解决方案是:
db.resellers.aggregate([
{
$unwind: "$clients"
},
{
$project: {
_id : 0,
teamMembers : "$clients.members"
}
},
{
$unwind: "$members"
},
{
$project: {
_id : 0,
userID : "$members.userID",
type : "$members.type"
}
}
]).pretty()
此解决方案仅返回成员列表,那么我需要做什么才能获得包含所有经销商、客户和成员的列表?
最佳答案
您可以使用 $reduce与 $concatArrays展平你的数据结构,然后运行 $unwind与 $replaceRoot获取每个文档的单个成员:
db.collection.aggregate([
{ "$project": {
"members": {
"$concatArrays": [
[{ "userID": "$userID", "userType": "$userType" }],
{ "$reduce": {
"input": "$clients",
"initialValue": [],
"in": {
"$concatArrays": [
"$$value",
[{ "userID": "$$this.userID", "userType": "$$this.userType" }],
"$$this.members"
]
}
}}
]
}
}},
{ "$unwind": "$members" },
{ "$replaceRoot": { "newRoot": "$members" }}
])
关于mongodb - 合并文档及其嵌套数组及其嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57101367/