为此,请aggregate()
在MongoDB中使用。首先让我们创建一个包含文档的集合-
> db.demo131.insertOne( ... { ... "_id": 101, ... "Details": [ ... { ... "PlayerScore": 500, ... "PlayerName": "Chris" ... }, ... { ... "PlayerScore": 400, ... "PlayerName": "David" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 } > db.demo131.insertOne( ... { ... "_id": 102, ... "Details": [ ... { ... "PlayerScore": 600, ... "PlayerName": "Chris" ... }, ... { ... "PlayerScore": 200, ... "PlayerName": "David" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 102 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo131.find();
这将产生以下输出-
{ "_id" : 101, "Details" : [ { "PlayerScore" : 500, "PlayerName" : "Chris" }, { "PlayerScore" : 400, "PlayerName" : "David" } ] } { "_id" : 102, "Details" : [ { "PlayerScore" : 600, "PlayerName" : "Chris" }, { "PlayerScore" : 200, "PlayerName" : "David" } ] }
以下是对数组中对象的各个属性求和的查询-
> db.demo131.aggregate([ ... { $unwind: "$Details" }, ... { ... $group: { ... _id:"$Details.PlayerName", ... Value:{$sum:"$Details.PlayerScore"} ... } ... }, ... { ... $group: { ... _id: 0, ... Details:{ $push: {Details:"$_id",Value:"$Value"}} ... } ... }, ... { ... $project:{Details:1,_id:0} ... } ])
这将产生以下输出-
{ "Details" : [ { "Details" : "David", "Value" : 600 }, { "Details" : "Chris", "Value" : 1100 } ] }