我正在尝试将blood_group
的值计入blood_category
的不同值中。从我的代码开始,我只能在num_stock
下计算blood_category
的总和。 blood_category:"platelet"
blood_group:"A",
num_stock:10
blood_category:"platelet"
blood_group:"B",
num_stock:10
blood_category:"whole blood"
blood_group:"A",
num_stock:20
blood_category:"whole blood"
blood_group:"B",
num_stock:20
的不同值。如何将计数存储在单个数组中?这是一个示例文档:
{_id: "platelets", A:10, B:10}, {_id: "whole blood", A:20, B:20},
我期望这样的输出:
Bloodinventory.aggregate([{$group: {_id : "$blood_category" , count :{$sum:"$num_stock"}}},{$sort: {_id: 1}}],function(err, inventory) {
res.json({ success: true, inventory: inventory });
});
我尝试过的代码:
{_id: "platelets", count:20},
{_id: "whole blood", count:40},
使用上面的示例,我的代码产生为:
position:sticky
答案 0 :(得分:0)
我无法通过当前文档结构获得所需的输出。但是,我能够通过修改后的文档结构来做到这一点,这可能会对您有所帮助。
这是您当前的文档结构:
db.blood.insertMany([
{ category: "platelet", group: "A", num_stock: 10 },
{ category: "platelet", group: "B", num_stock: 10 },
{ category: "whole blood", group: "A", num_stock: 20 },
{ category: "whole blood", group: "B", num_stock: 20 }
]);
这是修改后的文档结构:
db.blood.insertMany([
{ category: "platelet", stock: { "A": 10 }},
{ category: "platelet", stock: { "B": 10 }},
{ category: "whole blood", stock: { "A": 20 }},
{ category: "whole blood", stock: { "B": 20 }}
]);
使用修改后的文档结构,可以使用Aggregation Pipeline Operator $mergeObjects:
db.blood.aggregate( [
{ $group: { _id: "$category", mergedCategories: { $mergeObjects: "$stock" } } }
])
哪个给:
{ "_id" : "whole_blood", "mergedCategories" : { "A" : 20, "B" : 20 } }
{ "_id" : "platelet", "mergedCategories" : { "A" : 10, "B" : 10 } }
对于使用当前文档结构的解决方案,我将研究$mergeObjects中提供的示例。