为此,将$match和一起使用aggregate()
。让我们创建一个包含文档的集合-
> db.demo329.insertOne({"Name":"Chris","Age":21,"Marks":45}); { "acknowledged" : true, "insertedId" : ObjectId("5e516f28f8647eb59e56207d") } > db.demo329.insertOne({"Name":"David","Age":21,"Marks":56}); { "acknowledged" : true, "insertedId" : ObjectId("5e516f28f8647eb59e56207e") } > db.demo329.insertOne({"Name":"Mike","Age":21,"Marks":78}); { "acknowledged" : true, "insertedId" : ObjectId("5e516f29f8647eb59e56207f") } > db.demo329.insertOne({"Name":"David","Age":21,"Marks":89}); { "acknowledged" : true, "insertedId" : ObjectId("5e516f29f8647eb59e562080") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo329.find().pretty();
这将产生以下输出:
{ "_id" : ObjectId("5e516f28f8647eb59e56207d"), "Name" : "Chris", "Age" : 21, "Marks" : 45 } { "_id" : ObjectId("5e516f28f8647eb59e56207e"), "Name" : "David", "Age" : 21, "Marks" : 56 } { "_id" : ObjectId("5e516f29f8647eb59e56207f"), "Name" : "Mike", "Age" : 21, "Marks" : 78 } { "_id" : ObjectId("5e516f29f8647eb59e562080"), "Name" : "David", "Age" : 21, "Marks" : 89 }
以下是对键值求和的查询-
> db.demo329.aggregate([ ... { ... $match: { ... $and: [ ... { 'Name': 'David'}, ... { Age:21} .. ] ... } ... }, ... { ... $group: { ... _id: null, ... TotalMarks: { $sum: "$Marks" } ... } ... } ... ])
这将产生以下输出-
{ "_id" : null, "TotalMarks" : 145 }