跨索引获取数组字段的单一聚合
为了获得跨索引的数组字段的单一聚合,让我们举个例子并使用一些文档创建一个集合。
以下是使用文档创建集合的查询
> 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" ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP