MongoDB查询以将文档中特定字段的值相加
让我们创建一个包含文档的集合-
> db.demo677.insertOne({Value:10}); { "acknowledged" : true, "insertedId" : ObjectId("5ea421f404263e90dac943f8") } > db.demo677.insertOne({Value:50}); { "acknowledged" : true, "insertedId" : ObjectId("5ea421f704263e90dac943f9") } > db.demo677.insertOne({Value:20}); { "acknowledged" : true, "insertedId" : ObjectId("5ea421fa04263e90dac943fa") } > db.demo677.insertOne({Value:20}); { "acknowledged" : true, "insertedId" : ObjectId("5ea421fe04263e90dac943fb") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo677.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea421f404263e90dac943f8"), "Value" : 10 } { "_id" : ObjectId("5ea421f704263e90dac943f9"), "Value" : 50 } { "_id" : ObjectId("5ea421fa04263e90dac943fa"), "Value" : 20 } { "_id" : ObjectId("5ea421fe04263e90dac943fb"), "Value" : 20 }
以下是将特定字段的值相加的查询-
> db.demo677.aggregate({ $group: { _id : null, sum : { $sum: "$Value" } } });
这将产生以下输出-
{ "_id" : null, "sum" : 100 }