MongoDB - 查询无法在2.6中运行

时间:2014-09-18 11:40:28

标签: mongodb mongodb-query

我目前正在将我们的数据库从Mongo 2.4.9迁移到2.6.4。

我有一个奇怪的情况,在2.4中给出好结果的查询在2.6中没有返回文档。

有问题的查询:

var dbSearch = {
    created: { $gte: new Date(1409815194808) },
    geolocation: {
        $geoWithin: {
            $center: [ [ 4.895167900000001, 52.3702157 ], 0.1125 ]
        }
    }
};
该集合上的

是以下(相关)索引:

{ "v" : 1, "key" : { "created" : -1 }, "name" : "createdIndex", "ns" : "prod.search", "background" : true }
{ "v" : 1, "key" : { "geolocation" : "2d", "created" : -1 }, "name" : "geolocationCreatedIndex", "ns" : "prod.search" }

对Mongo 2.6运行此查询会提供以下查询日志:

{ created: { $gte: new Date(1409815194808) }, geolocation: { $geoWithin: { $center: [ [ 4.895167900000001, 52.3702157 ], 0.1125 ] } } } 
planSummary: IXSCAN { created: -1 } ntoreturn:0 ntoskip:0 keyUpdates:0 numYields:0 locks(micros) r:8196 nreturned:0 reslen:20 8ms

我使用node-mongodb-native模块使用NodeJS向数据库发出此查询。

请注意,当我删除其中一个搜索字段(createdgeolocation)时,查询将在2.4和2.6上生成正确的结果。组合(如上所述)在2.6

上没有结果

使用额外请求的信息进行编辑

解释mongo 2.4查询:

> db.search.find({created: { $gte: new Date(1409815194808) }, geolocation: {$geoWithin: {$center: [ [ 4.895167900000001, 52.3702157 ], 0.1125 ] } } }).explain()
{
    "cursor" : "GeoBrowse-circle",
    "isMultiKey" : false,
    "n" : 321,
    "nscannedObjects" : 321,
    "nscanned" : 321,
    "nscannedObjectsAllPlans" : 321,
    "nscannedAllPlans" : 321,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 69,
    "indexBounds" : {
        "geolocation" : [ ]
    },
    "lookedAt" : NumberLong(8940),
    "matchesPerfd" : NumberLong(8538),
    "objectsLoaded" : NumberLong(8538),
    "pointsLoaded" : NumberLong(0),
    "pointsSavedForYield" : NumberLong(0),
    "pointsChangedOnYield" : NumberLong(0),
    "pointsRemovedOnYield" : NumberLong(0),
    "server" : "ubmongo24.local:27017"
}

解释mongo 2.6查询:

> db.search.find({created: { $gte: new Date(1409815194808) }, geolocation: {$geoWithin: {$center: [ [ 4.895167900000001, 52.3702157 ], 0.1125 ] } } }).explain();
{
    "cursor" : "BtreeCursor createdIndex",
    "isMultiKey" : false,
    "n" : 0,
    "nscannedObjects" : 1403,
    "nscanned" : 1403,
    "nscannedObjectsAllPlans" : 2808,
    "nscannedAllPlans" : 2808,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 21,
    "nChunkSkips" : 0,
    "millis" : 8,
    "indexBounds" : {
        "created" : [
            [
                ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ"),
                ISODate("2014-09-04T07:19:54.808Z")
            ]
        ]
    },
    "server" : "ubmongo26.local:27017",
    "filterSet" : false
}

1 个答案:

答案 0 :(得分:1)

根据解释输出,问题似乎是查询优化器选择的索引(在2.6中进行了大量修改 - 主要是为了更好,但它确实意味着有新的边缘情况)。它使用单个字段createdIndex而不是2.4

中使用的复合索引

尝试在2.6(geolocationCreatedIndex)中隐藏.hint({ "geolocation" : "2d", "created" : -1 })索引并查看是否可以解决您的问题 - 它默认选择createdIndex,因此根本不使用地理索引