为此使用MongoDB聚合,并在其中使用$组。让我们创建一个包含文档的集合-
> db.demo649.insertOne( ... { "_id" : 101, "Names" : [ "John", "Bob", "Bob", "Robert" ], "CountryName" : "US" } ... ); { "acknowledged" : true, "insertedId" : 101 } > > db.demo649.insertOne({ "_id" :102, "Names" : [ "John", "Robert" ], "CountryName" : "UK"}); { "acknowledged" : true, "insertedId" : 102 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo649.find();
这将产生以下输出-
{ "_id" : 101, "Names" : [ "John", "Bob", "Bob", "Robert" ], "CountryName" : "US" } { "_id" : 102, "Names" : [ "John", "Robert" ], "CountryName" : "UK" }
以下是对聚合组的查询-
> db.demo649.aggregate( ... { $unwind : "$Names"}, ... { $group : { _id : "$_id" , Names : { $addToSet : "$Names" } , ... CountryName : { $first : "$CountryName" }}} ... )
这将产生以下输出-
{ "_id" : 102, "Names" : [ "Robert", "John" ], "CountryName" : "UK" } { "_id" : 101, "Names" : [ "Robert", "Bob", "John" ], "CountryName" : "US" }