获取跨索引数组字段的不同聚合

mongodbbig data analyticsdatabase更新于 2026/1/16 18:07:17

为了获取跨索引数组字段的不同聚合,我们举个例子,创建一个包含一些文档的集合。

以下是创建包含文档的集合的查询

> 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" ]

相关文章