Mongodb - increasing performance using compound index when pagination

129 views Asked by At

I'm newbie to mongodb and I need help about increasing performance for queries using compound indexes.

I am using pagination using "_id" field. Query:

db.data.find( {"$or": [ { "cat": "5" }, {"cat": "6" } ] }, {"style": "3"}, 
              {"area": "London"}, {"_id": {"$lt": 103}).sort( { "_id": 1 } ).limit(30)

style and area can be optional so these are also possible.

db.data.find( {"$or": [ { "cat": "5" }, {"cat": "6" } ] },  
              {"area": "London"}, {"_id": {"$lt": 103}).sort( { "_id": 1 } ).limit(30)

db.data.find( {"$or": [ { "cat": "5" }, {"cat": "6" } ] }, {"style": "3"}, 
              {"_id": {"$lt": 103}).sort( { "_id": 1 } ).limit(30)

db.data.find( {"$or": [ { "cat": "5" }, {"cat": "6" } ] }, 
              {"_id": {"$lt": 103}).sort( { "_id": 1 } ).limit(30)

Will these queries be ok with this compound index, or do I need more additional index?

{ "cat": 1, "style": 1, "area": 1, "_id": 1 }

Edit

I'm not sure which of these index would be efficient for queries.

{ "cat": 1, "style": 1, "area": 1, "_id": 1 } or
{ "_id": 1, "cat": 1, "style": 1, "area": 1 }

Number of styles: 16

Number of Areas: 50

Number of id: 10 million

1

There are 1 answers

7
Disposer On

use

{ "_id": 1, "cat": 1, "style": 1, "area": 1 }

ObjectId has this structure:

0 1 2 3   | 4 5 6   | 7 8 | 9 10 11
Timestamp | Machine | PID | Increment

because the timestamp comes first in above structure, it will sort in roughly insertion order.

When id came first in index, it will reduce your looking objects.