我正在尝试根据他们的itemName对集合进行分组
这是一个示例json
{
"_id" : ObjectId("5d7e3f1b2344e220289d2631"),
"itemName" : "Biscuit",
"itemSellingPrice" : "10",
"itemPurchasePrice" : "20",
"itemAveragePurchasePrice" : "20",
"itemBaseUnit" : "pcs",
"itemCategory" : "Bakery",
"itemReorderPoint" : "10",
"itemTotalQuantity" : "20",
"itemSumQuantity" : "20",
"itemLocation" : "1",
"itemSubLocation" : "Severino Reyes",
"itemDateCreated" : ISODate("2019-09-15T13:39:39.650Z"),
"itemID" : 232,
"__v" : 0
},
{
"_id" : ObjectId("5d7e3f202344e220289d2638"),
"itemName" : "Biscuit",
"itemSellingPrice" : "10",
"itemPurchasePrice" : "20",
"itemAveragePurchasePrice" : "20",
"itemBaseUnit" : "pcs",
"itemCategory" : "Bakery",
"itemReorderPoint" : "10",
"itemTotalQuantity" : "20",
"itemSumQuantity" : "100",
"itemLocation" : "1",
"itemSubLocation" : "Tomas Mapua",
"itemDateCreated" : ISODate("2019-09-15T13:39:39.650Z"),
"itemID" : 233,
"__v" : 0
}
截至目前,我有8条记录具有相同的“ itemName”:“饼干”
到目前为止,我的查询是这样的
db.getCollection('itemmodels').aggregate( [
{ "$match": { "itemLocation" : "1"} },
{"$group":
{
"_id": "$itemName",
"totalQuantity": {"$sum": "$itemSumQuantity"}
}}
] );
我正在尝试获取这8条记录的$ itemSumQuantity总和。 我也试图按原样显示其他数据。
这是我想要的示例输出
{
"itemName" : "Biscuit",
"itemSellingPrice" : "10",
"itemPurchasePrice" : "20",
"itemAveragePurchasePrice" : "20",
"itemBaseUnit" : "pcs",
"itemCategory" : "Bakery",
"itemReorderPoint" : "10",
"itemTotalQuantity" : "20",
"itemSumQuantity" : "120",
"itemLocation" : "1",
"numOfDuplicates": 8
}
因为第一个json数量是20,第二个json数量是100,所以它变成120
知道如何执行此操作吗?我找不到任何group accumulator才能得到想要的结果。
注意:总和对于数量都不起作用