对于此类文档分组,请在MongoDBgregation()中使用$group。让我们创建一个包含文档的集合-
> db.demo602.insertOne({id:1,Name:"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e960080ed011c280a0905c9") } > db.demo602.insertOne({id:2,Name:"David"});{ "acknowledged" : true, "insertedId" : ObjectId("5e960086ed011c280a0905ca") } > db.demo602.insertOne({id:1,Name:"Bob"});{ "acknowledged" : true, "insertedId" : ObjectId("5e96008ced011c280a0905cb") } > db.demo602.insertOne({id:3,Name:"Mike"});{ "acknowledged" : true, "insertedId" : ObjectId("5e960092ed011c280a0905cc") } > db.demo602.insertOne({id:2,Name:"John"});{ "acknowledged" : true, "insertedId" : ObjectId("5e960099ed011c280a0905cd") } > db.demo602.insertOne({id:1,Name:"Sam"});{ "acknowledged" : true, "insertedId" : ObjectId("5e9600a1ed011c280a0905ce") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo602.find();
这将产生以下输出-
{ "_id" : ObjectId("5e960080ed011c280a0905c9"), "id" : 1, "Name" : "Chris" } { "_id" : ObjectId("5e960086ed011c280a0905ca"), "id" : 2, "Name" : "David" } { "_id" : ObjectId("5e96008ced011c280a0905cb"), "id" : 1, "Name" : "Bob" } { "_id" : ObjectId("5e960092ed011c280a0905cc"), "id" : 3, "Name" : "Mike" } { "_id" : ObjectId("5e960099ed011c280a0905cd"), "id" : 2, "Name" : "John" } { "_id" : ObjectId("5e9600a1ed011c280a0905ce"), "id" : 1, "Name" : "Sam" }
以下是聚合不同文档中具有相似ID的元素的查询-
> db.demo602.aggregate([ ... { $group: { ... '_id': {id:"$id", "Name" : "$Name"}, ... "count" : { "$sum": 1 } ... }}, ... { $group: { ... '_id': "$_id.id", ... "ListOfName" : {"$push" : {Name:"$_id.Name", Frequency: "$count"}} ... }}, ... ], ... {'allowDiskUse': true} ... );
这将产生以下输出-
{ "_id" : 2, "ListOfName" : [ { "Name" : "John", "Frequency" : 1 }, { "Name" : "David", "Frequency" : 1 } ] } { "_id" : 3, "ListOfName" : [ { "Name" : "Mike", "Frequency" : 1 } ] } { "_id" : 1, "ListOfName" : [ { "Name" : "Sam", "Frequency" : 1 }, { "Name" : "Bob", "Frequency" : 1 }, { "Name" : "Chris", "Frequency" : 1 } ] }