我有以下收藏(以Json格式)-
/* 1 */
{
"_id" : NumberLong(1111),
"valueArray" : [
{
"accountNumber" : NumberLong(12345),
"levels" : [
1,
13
]
},
{
"accountNumber" : NumberLong(67890),
"levels" : [
2
]
}
]
}
/* 2 */
{
"_id" : NumberLong(2222),
"valueArray" : [
{
"accountNumber" : NumberLong(33333),
"levels" : [
13,
1
]
},
{
"accountNumber" : NumberLong(33333),
"levels" : [
8
]
},
{
"accountNumber" : NumberLong(44444),
"levels" : [
5
]
}
]
}
请注意accountNumber相同的第二个文档(33333)。我想将这些合并为单个条目。输出应类似于-
/* 1 */
{
"_id" : NumberLong(1111),
"valueArray" : [
{
"accountNumber" : NumberLong(12345),
"levels" : [
1,
13
]
},
{
"accountNumber" : NumberLong(67890),
"levels" : [
2
]
}
]
}
/* 2 */
{
"_id" : NumberLong(2222),
"valueArray" : [
{
"accountNumber" : NumberLong(33333),
"levels" : [
13,
1,
8
]
},
{
"accountNumber" : NumberLong(44444),
"levels" : [
5
]
}
]
}
我尝试了多种方法$ concatArrays,$ setUnion等,但最终却遇到一些错误。即使我能够得到一些输出,它也不是必需的格式。
有人可以在这里帮忙吗?
答案 0 :(得分:1)
您可以使用双$unwind来获取每个valueArray.accountNumber
的单个文档,并使用双$group来汇总这些值,首先依次是accountNumber
和_id
,尝试:
db.col.aggregate([
{
$unwind: "$valueArray"
},
{
$unwind: "$valueArray.levels"
},
{
$group: {
_id: {
_id: "$_id",
accountNumber: "$valueArray.accountNumber"
},
levels: { $push: "$valueArray.levels" }
}
},
{
$group: {
_id: "$_id._id",
valueArray: {
$push: { accountNumber: "$_id.accountNumber", levels: "$levels" }
}
}
}
])