我是MongoDB新手,所以如果我错过了一些文档中的东西,请原谅我。我的收藏是这样的:
{
"_id" : ObjectId("57553e7015e4117a4343c18c"),
"BuyingPrice" : 55.5,
"Quantity" : NumberLong(1),,
"Brand" : "Ranamina",
"Amount" : 79.99,
"Profit" : 24.49,
"ProductId" : NumberLong(55319),}在计算了每个品牌的总数量后,我想看看每个品牌的产品数量。
我想看到结果
{"Quantity": 1982,
"Amount": 155,
"Number_of_product" :12,
"_id":{"Brand": "Ranamina"}
}这是我的密码:
collection_test.aggregate([
{
'$group': {
'_id': {
'Brand': '$Brand',
},
'Amount': {'$sum': '$Amount'},
'product': {'$addToSet': '$ProductId'},
'Amount_sum': {'$addToSet': '$Amount'},
},
},
{'$group': {
'_id': {'Brand': '$_id.Brand', 'ProductId': '$product'},
}
},
{
'$project': {'count': {'$size': '$_id.ProductId'},
'Groups': '$_id.Groups', '_id': 0, 'Amount_sum':1,
}}
])我用的是分组法,但我无法获得总金额和总利润。有办法进入这些吗?
发布于 2016-10-28 09:55:06
这个怎么样?:
collection_test.aggregate([
{
'$group': {
'_id': {
'Brand': '$Brand',
},
'Amount': {'$sum': '$Amount'},
'Quantity': {'$sum': '$Quantity'},
'product': {'$addToSet': '$ProductId'},
},
},
{
'$project': {
'Quantity': True,
'Amount': True,
'Number_of_product': {'$size': '$product'}
}
}])你绝对不需要两个"$group“阶段。
https://stackoverflow.com/questions/40301224
复制相似问题