如何对 MongoDB 子文档中的每个字段求和?
要对子文档中的每个字段求和,请使用集框架。让我们首先创建一个包含文档的集合——
> db.sumEveryFieldDemo.insertOne( ... { ... "_id":101, ... "PlayerDetails": [ ... {"PlayerName":"John","PlayerScore":1000}, ... {"PlayerName":"Carol","PlayerScore":2000}, ... {"PlayerName":"Sam","PlayerScore":3000} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
以下是有助于使用 find() 方法显示集合中所有文档的查询——
> db.sumEveryFieldDemo.find().pretty();
将生成以下输出——
{ "_id" : 101, "PlayerDetails" : [ { "PlayerName" : "John", "PlayerScore" : 1000 }, { "PlayerName" : "Carol", "PlayerScore" : 2000 }, { "PlayerName" : "Sam", "PlayerScore" : 3000 } ] }
以下是有助于对 MongoDB 的子文档求和的查询——
> db.sumEveryFieldDemo.aggregate( [ ... { $unwind: "$PlayerDetails" }, ... { $group: { ... _id: '$_id', ... sum: { $sum: '$PlayerDetails.PlayerScore' } ... } } ... ] ).pretty();
将生成以下输出——
{ "_id" : 101, "sum" : 6000 }
广告