1
在过去的几个小时里,我一直在碰撞着这个东西,不能把头绕在里面。也许有人可以帮忙。我收集了以下内容。mongodb组和总和?
{
"smallparts": [
{ "quantity": "10", "part": "test1" },
{ "quantity": "10", "part": "test2" }
]
},
{
"smallparts": [
{ "quantity": "10", "part": "test3" }
]
},
{
"smallparts": [
{ "quantity": "10", "part": "test1" },
{ "quantity": "10", "part": "test2" }
]
}
当尝试以下添加数量我不能正确。
collection.aggregate(
// Unwind the array
{ "$unwind":"$smallparts" },
// Group the products
{
"$group":
{
"_id":
{
"part": "$smallparts.part",
"total": "$smallparts.quantity",
}
},
},
我的输出是这是错误的。 TEST1和TEST2应该是20
{
"data": [
{
"_id": {
"part": "test3",
"total": "10"
}
},
{
"_id": {
"part": "test2",
"total": "10"
}
},
{
"_id": {
"part": "test1",
"total": "10"
}
}
]
}
我也试过,但得到一个空数组。
collection.aggregate(
//放松阵列 { “$开卷”: “$ smallparts”},// Group the products { "$group": { "_id": { "part": "$smallparts.part", "total": "$smallparts.quantity", sum: { $sum: "$smallparts.quantity" } } },
感谢您的帮助