要选择按MongoDB中的字段分组的文档,请使用$group和$project。首先让我们创建一个包含文档的集合-
> db.demo540.insertOne({id:1,"Name":"Chris","CountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8ca368ef4dcbee04fbbc0e") } > db.demo540.insertOne({id:1,"Name":"Chris","CountryName":"UK"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8ca36bef4dcbee04fbbc0f") } > db.demo540.insertOne({id:1,"Name":"Chris","CountryName":"AUS"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8ca370ef4dcbee04fbbc10") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo540.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8ca368ef4dcbee04fbbc0e"), "id" : 1, "Name" : "Chris", "CountryName" : "US" } { "_id" : ObjectId("5e8ca36bef4dcbee04fbbc0f"), "id" : 1, "Name" : "Chris", "CountryName" : "UK" } { "_id" : ObjectId("5e8ca370ef4dcbee04fbbc10"), "id" : 1, "Name" : "Chris", "CountryName" : "AUS" }
以下是查询以选择按字段分组的文档-
> var query= [ ... { ... "$group": { ... "_id": { ... "id": "$id", ... "Name": "$Name" ... }, ... "details": { ... "$push": { ... ... "CountryName": "$CountryName" ... ... } ... } ... } ... }, ... { ... "$project": { ... "_id": "$_id.id", ... "Name": "$_id.Name", ... "details": 1 ... } ... } ... ]; > db.demo540.aggregate(q).pretty();
这将产生以下输出-
{ "details" : [ { "Name" : "Chris", "CountryName" : "US" }, { "Name" : "Chris", "CountryName" : "UK" }, { "Name" : "Chris", "CountryName" : "AUS" } ], "_id" : 1, "Name" : "Chris" }