首页 > 解决方案 > MongoDB在聚合中排序和查找之间的区别

问题描述

我有一个复杂的查询,它包含几个“阶段”(匹配、排序、偏移、限制),但是当我在聚合管道中执行它时需要 10 分钟,但在 find(...).skip.limit.sort 中只需 0.5 秒,为什么会这样?

附加信息:
集合大小:20 000 000
存储大小:33GB
索引:16
平均文档大小:6kb
文档结构复杂,内部对象和数组很多。

匹配/查找阶段示例(查询中的所有字段都已编入索引):

{
  "Target._id":{
    "$in":[
      CSUUID("73aedf6b-dba7-4905-5187-08d7d623e1a0")
    ]
  },
  "StartDateTime":{
    "$gte":ISODate("2020-03-31T21:00:00Z"),
    "$lte":ISODate("9999-12-30T22:00:00Z")
  },
  "$expr":{
    "$switch":{
      "branches":[
        {
          "case":{
            "$and":[
              {
                "$gte":[
                  "$StartDateTime",
                  ISODate("2020-03-31T21:00:00Z")
                ]
              },
              {
                "$lte":[
                  "$StartDateTime",
                  ISODate("9999-12-30T22:00:00Z")
                ]
              },
              {
                "$in":[
                  "$Target._id",
                  [
                    CSUUID("73aedf6b-dba7-4905-5187-08d7d623e1a0")
                  ]
                ]
              }
            ]
          },
          "then":true
        }
      ],
      "default":false
    }
  }
}

标签: mongodbmongodb-.net-driver

解决方案


推荐阅读