【问题标题】:Index on multi-field object in mongoDBmongoDB中多字段对象的索引
【发布时间】:2014-04-22 14:31:36
【问题描述】:

我有一个由 map reduce 调用生成的集合,键由两个字段组成,所以我的 id 设置如下:

{
   "_id": {
     "ts": ISODate("2014-04-22T13: 46: 00.0Z"),
     "own": "LP2" 
  }
  //... my fields
}

在“_id”上自动构建索引:

{
   "v": NumberInt(1),
   "key": {
     "_id": NumberInt(1) 
  },
   "ns": "DB.COLLECTION_NAME",
   "name": "_id_" 
}

但是当我进行查询时,我经常想对“ts”字段进行排序。

我知道我可以在它上面构建一个索引,但我想知道“_id”上的索引是否已经支持它,就像复合索引一样。这样可以节省插入时间。

提前感谢您的回答。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    我不相信它会。对此进行测试的方法是插入一些测试数据并尝试一些测试查询。当我运行db.collectionname.find({}).sort({"_id.ts":-1}).explain() 时,很明显它没有使用索引进行排序:

    {
        "cursor" : "BasicCursor",
        "isMultiKey" : false,
        "n" : 13,
        "nscannedObjects" : 13,
        "nscanned" : 13,
        "nscannedObjectsAllPlans" : 13,
        "nscannedAllPlans" : 13,
        "scanAndOrder" : true,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "server" : "local:27017",
        "filterSet" : false
    }
    

    请注意,scanandorder 为真。

    添加一个新索引后,直接索引 _id.ts 我看到了更好的结果:

    db.collectionname.ensureIndex({"_id.ts":1})
    db.collectionname.find({}).sort({"_id.ts":-1}).explain()
    {
        "cursor" : "BtreeCursor _id.ts_1 reverse",
        "isMultiKey" : false,
        "n" : 13,
        "nscannedObjects" : 13,
        "nscanned" : 13,
        "nscannedObjectsAllPlans" : 13,
        "nscannedAllPlans" : 13,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
            "_id.ts" : [
                [
                    {
                        "$maxElement" : 1
                    },
                    {
                        "$minElement" : 1
                    }
                ]
            ]
        },
        "server" : "local:27017",
        "filterSet" : false
    }
    

    请注意,scanandorder 现在为 false。

    【讨论】:

      猜你喜欢
      • 2016-08-03
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 2016-01-18
      • 2012-02-22
      • 2012-09-16
      • 1970-01-01
      相关资源
      最近更新 更多