简体   繁体   中英

Mongodb indexing with $or operator

We are using mongodb $or operator for filtering data. The following query is not using any of the indexes.

{
    data.username: "xxxxx",
    $or: [
        {
            data.timestamp: {
                $gte: 1428405480000,
                $lte: 1428406380000 
            },
            data.finished: false 
        },
        {
            data.timestamp: {
                $gte: 1428319980000,
                $lte: 1428406380000 
            },
            data.finished: true 
        }
    ]
}

We have defined following indexes on the collection:

index1

{ 
    "data.username" : 1.0, 
    "data.uuid" : 1.0, 
    "data.timestamp" : -1.0
}

index2

{ 
    "data.username" : 1.0, 
    "data.userid" : 1.0, 
    "data.timestamp" : 1.0, 
    "data.finished" : 1.0
}

index3

{ 
    "data.username" : 1.0, 
    "data.timestamp" : 1.0, 
    "data.finished" : 1.0
}

index4

{ 
    "data.username" : 1, 
    "data.finished" : 1, 
    "data.timestamp" : 1
}

None of the above indexes is being used by MongoDB. We are using WiredTiger storage engine. Result of the explain command returns explain.queryPlanner. indexFilterSet = false

As highlighted by joao, the documentatation states that when evaluating the clauses in the $or expression, MongoDB either performs a collection scan or, if all the clauses are supported by indexes, MongoDB performs index scans. That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes. Otherwise, MongoDB will perform a collection scan.

So in short, you should add the following indices:

{ 
    "data.username" : 1.0
}

{  
   "data.userid" : 1.0  
}

{ 
   "data.timestamp" : 1.0
}

{ 
    "data.finished" : 1.0
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM