【发布时间】:2014-06-08 01:21:03
【问题描述】:
在过去的几个小时里,我一直在纠结这个问题,无法解决这个问题。也许有人可以帮忙。我有一个包含以下内容的集合。
{
"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(
//展开数组 { "$unwind":"$smallparts" },// Group the products { "$group": { "_id": { "part": "$smallparts.part", "total": "$smallparts.quantity", sum: { $sum: "$smallparts.quantity" } } },
感谢您的帮助。
【问题讨论】:
标签: javascript node.js mongodb