【问题标题】:MongoDB distinct on array of embedded document doesn't use indexMongoDB在嵌入式文档数组上不同不使用索引
【发布时间】:2016-04-24 15:41:00
【问题描述】:

假设我有一个这样的文档集合,其中的 stock 字段包含一组嵌入文档:

{
  _id: 1,
  item: "abc",
  stock: [
      { size: "S", color: "red", quantity: 25 },
      { size: "S", color: "blue", quantity: 10 },
      { size: "M", color: "blue", quantity: 50 }
  ]
}

我创建了一个这样的多键索引:

db.items.createIndex("stock.size")

但是当我跑步时:

db.runCommand({distinct: "items", key: "stock.size"})

它返回:

{
    "values" : [
        "S", "M"
    ],
    "stats" : {
        "n" : 1730969,
        "nscanned" : 0,
        "nscannedObjects" : 1730969,
        "timems" : 13716,
        "planSummary" : "COLLSCAN"
    },
    "ok" : 1
}

它执行了整个集合扫描并且没有使用索引。我可以以某种方式加速对子文档数组的不同查询吗?

谢谢

【问题讨论】:

    标签: mongodb indexing


    【解决方案1】:

    我有同样的问题,只是发帖让你知道,从 3.2 开始,你可以使用解释来获得更多关于执行的细节:

    db.items.explain().distinct('stock.size');
    

    我测试了我的索引,它在过滤时确实有效,但在使用 distinct() 时无效。希望它会很快:/

    【讨论】:

      猜你喜欢
      • 2013-10-16
      • 2012-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多