MongoDB 聚合在一个数组的对象上汇总各个文档的单个属性
为此,在 MongoDB 中使用 aggregate()。让我们首先创建一个包含文档的集合 -
> 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 } ] }
广告