如何在 MongoDB 中按字段对文档进行分组并选择?
要按 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" }
广告