mongodbindexingcompound-indexnosql

MongoDB Indexes, is it possible to create both normal & compound at the same time?


I have to create indexes for a MongoDb collection:

Users

1.The 30% of the queries are {_id, token,device_id}

2.Other common queries (30%) are {_id, token}

3.And the rest (40%) are queries using individually: {_id} {device_id} {userid} {facebook_id}

I don´t know how to manage that. I am almost sure that i need to create a compound index on {_id:"1" , token:"1",device_id:"1"} . My questions are:

a)Would the compound index optimize the first and the second case,right?

b)What should i do with the case 3?Create indexes for each field?

Thanks!


Solution

  • Yes, it's possible to create a compound index on fields and index those fields separately.

    If you create a compound index like this:

    db.coll.ensureIndex({_id : 1, token : 1,device_id: 1}); 
    

    This index will support queries on prefix on the index fields: The following queres will be supported by the compound index:

    db.coll.find({ _id : ObjectId(....), token : "foo"});
    db.coll.find({ _id : ObjectId(....), token : "foo", device_id: 12345});
    

    When you have a compound index on those fields, you can also create an index on a single field (e.g. on fields like token or device_id).

    As Sammaye suggested in the comments. The last case will probably require 3 separate indexes on device_id, userid and facebook_id fields (a unique index on _id field is created by default, so you don't need to create it).