我正在尝试使用聚合框架创建查询,但无法获得所需的结果。 我有一个代理商集合,每个代理商都有一个客户列表,每个客户都有一个成员列表,结构如下:
[
{
"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()
此解决方案仅返回成员列表,那么我需要做些什么来获得包含所有经销商,客户和成员的列表?
答案 0 :(得分:2)
答案 1 :(得分:1)
好吧,我在此向您介绍$project
阶段中的所有内容。享受吧!
[
{
"$project": {
"members": {
"$reduce": {
"input": {
"$map": {
"input": "$clients",
"in": {
"$concatArrays": [
[
{
"userID": "$userID",
"userType": "$userType"
},
{
"userID": "$$this.userID",
"userType": "$$this.userType"
}
],
"$$this.members"
]
}
}
},
"initialValue": [
],
"in": {
"$concatArrays": [
"$$this",
"$$value"
]
}
}
}
}
}
]