在 MongoDB 中按另一个字段对值进行分组?
要按另一个字段进行分组,使用 $group 和 $project。我们首先创建一个包含文档的集合 −
> db.demo374.insertOne( ... { ... ... "Name" : "Chris", ... "HobbyDetails" : [ ... "Reading Book", ... "Playing Football" ... ], ... "CountryName" : "US" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5a04402ae06a1609a00b04") } > db.demo374.insertOne( ... { ... ... "Name" : "Chris", ... "HobbyDetails" : [ ... "Browsing Internet", ... "Playing Football" ... ], ... "CountryName" : "US" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5a04402ae06a1609a00b05") }
使用 find() 方法显示集合中的所有文档 −
> db.demo374.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e5a04402ae06a1609a00b04"), "Name" : "Chris", "HobbyDetails" : [ "Reading Book", "Playing Football" ], "CountryName" : "US" } { "_id" : ObjectId("5e5a04402ae06a1609a00b05"), "Name" : "Chris", "HobbyDetails" : [ "Browsing Internet", "Playing Football" ], "CountryName" : "US" }
下面是在 MongoDB 中按另一个字段查找值的查询 −
> db.demo374.aggregate([ ... {$match : { "CountryName" : "US"}}, ... {$group : {"_id" : "$Name", "HobbyDetails" : {$addToSet : "$HobbyDetails"}}}, ... {$project : {"_id" : 0, "Name" : "$_id", "HobbyDetails" : {$reduce : {input : "$HobbyDetails", initialValue : [], in: { $concatArrays : ["$$value", "$$this"] }}}}} ... ]).pretty()
这将产生以下输出 −
{ "Name" : "Chris", "HobbyDetails" : [ "Browsing Internet", "Playing Football", "Reading Book", "Playing Football" ] }
广告