Mongodb索引聚合 [英] Mongodb indexing for aggregates
问题描述
我正在使用以下汇总,并希望了解为此建议的索引:
I'm using the following aggregate and wanted to see what would be the recommended indexes for this:
{
"$match" :
{
user : ObjectId(user_id),
type : 'item'
}
},
{ "$group" : {
_id : "$user",
size : { "$sum" : "$size" }
}
}
对用户和类型进行复合索引,然后对_id和大小进行另一个复合索引是太多还是必要的?
Would it be too much or necessary to do a compound index on user and type, then another compound index on _id and size?
推荐答案
您无法创建以描述方式工作的索引.运行聚合时,无法对管道步骤的输出之一进行索引".
You can't create an index that works the way you've described it. There's not a way to "index" one of the outputs of a pipeline step when running an aggregation.
有些聚合运算符可以工作使用MongoDB集合索引.
当前,它们包括:$match
,$sort
,$limit
和$skip
.
Currently, they include: $match
, $sort
, $limit
, and $skip
.
由于$match
是其中之一,因此您可以通过在两个字段上声明一个复合索引来受益于编写的聚合查询的性能,尤其是当您将$match
正确地放置在管道:
As $match
is one of them, the performance of the aggregation query you've written may benefit by declaring a compound index on the two fields, especially as you've correctly placed the $match
at the beginning of the pipeline:
db.theCollection.ensureIndex({user: 1, type: 1})
管道中的$group
步骤将获取来自$match
的结果,理想情况下,相对较快. :)
The $group
step in the pipeline will take the results from the $match
and ideally, be relatively quick. :)
这篇关于Mongodb索引聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!