聚合管道和索引 [英] Aggregation pipeline and indexes

查看:176
本文介绍了聚合管道和索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 http://docs.mongodb.org/manual/core/ index /#multikey-indexes ,可以使用多键索引在数组字段上创建索引。 http://docs.mongodb.org/manual/applications/ aggregation /#pipeline-operators-and-indexes 列出了在聚合框架中如何使用索引的一些方法。但是,有时我可能需要在数组字段上执行 $ unwind 来执行 $ group 。我的问题是,在管道中间操作多键索引(或任何使用此类数组字段的索引)仍然可以使用吗?

From http://docs.mongodb.org/manual/core/indexes/#multikey-indexes, it is possible to create an index on an array field using a multikey index. http://docs.mongodb.org/manual/applications/aggregation/#pipeline-operators-and-indexes lists some ways of how an index can be used in aggregation framework. However, there may be times that I may need to perform an $unwind on an array field to perform a $group. My question is, are multikey indexes (or any index using such array field) can still be used once they are operated on in the middle of the pipeline?

推荐答案

通常,只有可以展平为普通查询的管道运算符( $ match $ limit $ sort $ skip )将能够使用集合上的索引。这是2.4中添加的 $ geoNear 运算符必须位于管道开头的原因之一。

Generally, only pipeline operators that can be flattened to a normal query ($match, $limit, $sort, and $skip) will be able to use the indexes on a collection. This is one of the reasons the $geoNear operator added in 2.4 has to be at the start of the pipeline.

使用 $ project $ group $ unwind 索引不再有效/可用。

Once you mutate the documents with $project, $group, or $unwind the index is no longer valid/usable.

如果你有一个数组字段的索引,你仍然可以在 $ unwind 加快选择要管道的文档,然后使用第二个 $ match 进一步优化所选文档。

If you have an index on an array field you can still use it before the $unwind to speed up the selection of documents to pipeline and then further refine the selected documents with a second $match.

考虑以下文件:

{ tags: [ 'cat', 'bird', 'blue' ] }

索引标签

如果您只想对以 b 开头的标签进行分组,那么你可以执行如下聚合:

If you only wanted to group the tags starting with b then you could perform an aggregation like:

{ pipeline: [
      { $match : { tags : /^b/ } },
      { $unwind : '$tags' },
      { $match : { tags : /^b/ } },
      /* the rest */
  ] }

第一个 $ match 使用<$ c上的索引进行粗粒匹配$ C>标记。

$ unwind 之后的第二场比赛将无法使用索引(上面的文件现在是3个文档)但可以评估每个文档以过滤掉创建的额外文档(从示例中删除{tags:'cat'})。

The second match after the $unwind won't be able to use the index (the document above is now 3 documents) but can evaluate each of those documents to filter out the extra documents that get created (to remove { tags : 'cat' } from the example).

HTH - Rob。

HTH - Rob.

这篇关于聚合管道和索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆