首先,让我们创建一个包含文档的集合-
> db.demo99.insertOne( ... { ... ... 'Details': ... { ... 'X': ... { ... 'Values': [10,30,50], ... 'Number':3, ... }, ... 'Y': ... { ... 'Values': [1000, 180], ... 'Number': 2, ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2d91eab8903cdd865577b9") } > db.demo99.insertOne( ... { ... ... 'Details': ... { ... 'X': ... { ... 'Values': [100,300,500,6000], ... 'Number':4, ... }, ... 'Y': { ... 'Values': [10, 20,60], ... 'Number': 3, ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2d927bb8903cdd865577ba") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo99.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2d91eab8903cdd865577b9"), "Details" : { "X" : { "Values" : [ 10, 30, 50 ], "Number" : 3 }, "Y" : { "Values" : [ 1000, 180 ], "Number" : 2 } } } { "_id" : ObjectId("5e2d927bb8903cdd865577ba"), "Details" : { "X" : { "Values" : [ 100, 300, 500, 6000 ], "Number" : 4 }, "Y" : { "Values" : [ 10, 20, 60 ], "Number" : 3 } } }
以下是将聚合中的嵌套字段与数组中的计数值分组的查询-
> db.demo99.aggregate([ { $project: { Count: { $objectToArray: "$Details" } } }, { $unwind: "$Count" }, { $group: { _id: "$Count.k", count: { $sum: "$Count.v.Number"} } } ])
这将产生以下输出-
{ "_id" : "Y", "count" : 5 } { "_id" : "X", "count" : 7 }