要按另一个字段分组,请使用$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" ] }