MongoDB所有文档的字典列表中的值总和?
要汇总字典列表中的值总和,请使用$sum和aggregate()
。让我们创建一个包含文档的集合-
> db.demo117.insertOne(... {
... ID:101,
... Details:[
... {
... Name:'Chris',
... Value1:20,
... Value2:30,
... Value3:10
... },
... {
... Name:'David',
... Value1:10,
... Value2:50,
... Value3:30
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2f02ced8f64a552dae6361")
}
> db.demo117.insertOne(
... {
... ID:102,
... Details:[
... {
... Name:'Chris',
... Value1:20,
... Value2:10,
... Value3:20
... },
... {
... Name:'David',
... Value1:30,
... Value2:40,
... Value3:10
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2f02ced8f64a552dae6362")
}
在find()
方法的帮助下显示集合中的所有文档-
> db.demo117.find();
这将产生以下输出-
{"_id" : ObjectId("5e2f02ced8f64a552dae6361"), "ID" : 101, "Details" : [
{ "Name" : "Chris", "Value1" : 20, "Value2" : 30, "Value3" : 10 },
{ "Name" : "David", "Value1" : 10, "Value2" : 50, "Value3" : 30 }
]
}
{
"_id" : ObjectId("5e2f02ced8f64a552dae6362"), "ID" : 102, "Details" : [
{ "Name" : "Chris", "Value1" : 20, "Value2" : 10, "Value3" : 20 },
{ "Name" : "David", "Value1" : 30, "Value2" : 40, "Value3" : 10 }
]
}
以下是查询汇总所有文档的词典列表中的值的总和的查询-
> db.demo117.aggregate([{... $unwind: "$Details"
... }, {
... $group: {
... _id: "$Details.Name",
... "Value1": { $sum: "$Details.Value1" },
... "Value2": { $sum: "$Details.Value2" },
... "Value3": { $sum: "$Details.Value3" }
... }
... }])
这将产生以下输出-
{ "_id" : "David", "Value1" : 40, "Value2" : 90, "Value3" : 40 }{ "_id" : "Chris", "Value1" : 40, "Value2" : 40, "Value3" : 30 }
以上是 MongoDB所有文档的字典列表中的值总和? 的全部内容, 来源链接: utcz.com/z/316635.html