为了获得跨索引的数组字段的独特聚合,让我们举一个例子并创建包含一些文档的集合。
以下是使用文档创建集合的查询
> db.distinctAggregation.insertOne({"UserName":"Larry","UserPost":["Hi","Hello"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c98aefb330fd0aa0d2fe4c6") } > db.distinctAggregation.insertOne({"UserName":"Chris","UserPost":["Hi","Good Morning"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c98af0a330fd0aa0d2fe4c7") } > db.distinctAggregation.insertOne({"UserName":"Robert","UserPost":["Awesome"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c98af1e330fd0aa0d2fe4c8") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.distinctAggregation.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c98aefb330fd0aa0d2fe4c6"), "UserName" : "Larry", "UserPost" : [ "Hi", "Hello" ] } { "_id" : ObjectId("5c98af0a330fd0aa0d2fe4c7"), "UserName" : "Chris", "UserPost" : [ "Hi", "Good Morning" ] } { "_id" : ObjectId("5c98af1e330fd0aa0d2fe4c8"), "UserName" : "Robert", "UserPost" : [ "Awesome" ] }
以下是在数组字段上创建索引的查询
> db.distinctAggregation.ensureIndex({"UserPost":1}); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
以下是查询以获取跨索引的数组字段的不同集合的查询
> db.distinctAggregation.distinct("UserPost");
这将产生以下输出
[ "Awesome", "Good Morning", "Hello", "Hi" ]