Pawan
Pawan

Reputation: 32331

Can we apply index to match a certain value in mongoDB

i have a collection named users as shown below .

     db.users.find().pretty()
{
        "_id" : ObjectId("512efc206074b0e4bbdce792"),
        "login_id" : "dutchuser",
        "isBroker" : false

}

I want to apply index for this users collection with the login_id and isBroker field also .

db.users.ensureIndex( { "login_id": 1, "isBroker": 1 }, { unique: false } )

My concern is that most of the isBroker field has got a value of false . So is there any possibility that i can apply index in that way ??

Upvotes: 0

Views: 60

Answers (1)

WiredPrairie
WiredPrairie

Reputation: 59783

You cannot conditionally apply a filter to an index in MongoDB. While you could potentially restructure your data or introduce additional, potentially duplicate fields in your schema, I'm not convinced it's a reasonable "optimization."

Use db.stats() to actually measure the size of the database and db.{collectionname}.totalIndexSize() to see what the impact of having the index you proposed really is.

By using this index:

db.users.ensureIndex( { "login_id": 1, "isBroker": 1 }, { unique: false } )

You can only use queries that involve login_id and isBroker or just login_id. Depending on the types of queries that you run, you may also run into this currently open issue that might make a simple grouping/sorting on isBroker inefficient (or if at some point it becomes broker_type for example).

Upvotes: 1

Related Questions