合并文档及其嵌套数组和嵌套数组 [英] Merge documents with its nested arrays and their nested arrays
问题描述
我正在尝试使用聚合框架创建查询,但无法获得所需的结果.我有一个转销商集合,每个转销商都有一个客户列表,每个客户都有一个成员列表,结构如下:
I'm trying to create a query with the aggregation framework, but I could not get the result I want. I have a collection of resellers, each reseller have a list of clients, each clients have a list of members, the structure is as below :
[
{
"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"
}
]
我做了很多尝试,但没有得到这个结果.我最接近的解决方案是:
I did so many try but I did not to get this result. The closest solution that I did is :
db.resellers.aggregate([
{
$unwind: "$clients"
},
{
$project: {
_id : 0,
teamMembers : "$clients.members"
}
},
{
$unwind: "$members"
},
{
$project: {
_id : 0,
userID : "$members.userID",
type : "$members.type"
}
}
]).pretty()
此解决方案仅返回成员列表,那么我需要做些什么来获得包含所有经销商,客户和成员的列表?
This solution returns only the list of members, so what i have to do to get a list containing all the resellers, the clients and the members all together?
推荐答案
您可以使用 $ concatArrays a>整理数据结构,然后运行 $ unwind 带有 $ replaceRoot 的a>文件:
You can use $reduce with $concatArrays to flatten your data structure and then run $unwind with $replaceRoot to get single member per document:
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" }}
])
这篇关于合并文档及其嵌套数组和嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!