要汇总子文档中的每个字段,请使用聚合框架。首先让我们创建一个包含文档的集合-
> 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 }