MongoDB 查询使用带有终端命令的特定键值和吗?
为此,使用 $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 }
广告