若要使用文档的GROUP BY数组,请使用$group。让我们创建一个包含文档的集合-
>db.demo559.insertOne({details:[{Name:"Chris",Age:21},{Name:"Bob",Age:22},{Name:"Carol", Age:21},{Name:"Sam",Age:21}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e8f38d954b4472ed3e8e866") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo559.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e8f38d954b4472ed3e8e866"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 22 }, { "Name" : "Carol", "Age" : 21 }, { "Name" : "Sam", "Age" : 21 } ] }
以下是按文档数组分组的查询-
> db.demo559.aggregate([ ... { ... "$unwind": "$details" ... }, ... { ... "$group": { ... "_id": "$details.Age", ... "Count": { "$sum" : 1 } ... } ... }, ... { "$sort": { "_id" : 1 } } ... ])
这将产生以下输出-
{ "_id" : 21, "Count" : 3 } { "_id" : 22, "Count" : 1 }