为此,请aggregate()
在MongoDB中使用。首先让我们创建一个包含文档的集合-
> db.demo126.insertOne( ... { ... "StudentDetails" : { ... "Number" : 1, ... "OtherDetails" : [ ... { ... "Name" : "Chris", ... "Score" : 55 ... ... } ... ].. }} ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e304b3068e7f832db1a7f56") } > > > db.demo126.insertOne( ... { ... "StudentDetails" : { ... ... "Number" : 2, ... "OtherDetails" : [ ... { ... "Name" : "Chris", ... "Score" : 35 ... ... }, ... { ... "Name" : "David", ... "Score" : 87 ... } ... ... ] ... }} ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e304b3068e7f832db1a7f57") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo126.find();
这将产生以下输出-
{ "_id" : ObjectId("5e304b3068e7f832db1a7f56"), "StudentDetails" : { "Number" : 1, "OtherDetails" : [ { "Name" : "Chris", "Score" : 55 } ] } } { "_id" : ObjectId("5e304b3068e7f832db1a7f57"), "StudentDetails" : { "Number" : 2, "OtherDetails" : [ { "Name" : "Chris", "Score" : 35 }, { "Name" : "David", "Score" : 87 } ] } }
以下是基于数组值聚合的查询-
> db.demo126.aggregate([ ... { ... $unwind:"$StudentDetails.OtherDetails" ... }, ... { ... $group:{ ... _id:"$StudentDetails.OtherDetails.Name", ... quantity:{ ... $sum:"$StudentDetails.OtherDetails.Score" ... } ... } ... } ... ])
这将产生以下输出-
{ "_id" : "David", "quantity" : 87 } { "_id" : "Chris", "quantity" : 90 }