Dewfy
Dewfy

Reputation: 23624

mongodb index usage depends on notation

Saying I have compound _id on collection A:

{
    _id:{
       orgUnit:Int64
       ...
    }
}

Querying such shows that index is used:

db.A.find({_id:{orgUnit:1039}}).explain() 

...

    "indexBounds" : {
            "start" : {
                    "_id" : {
                            "orgUnit" : 1039
                    }
            },
            "end" : {
                    "_id" : {
                            "orgUnit" : 1039
                    }
            }

But when I changing query to "dot notation" shows that query became plain.

db.A.find({"_id.orgUnit":1039}).explain()
...
"indexBounds" : {

},

What is wrong with dot notation? And the main: How to leverage indexing to allow me find by "_id.orgUnit"

Upvotes: 0

Views: 156

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311935

You would need to create a separate index on '_id.orgUnit' to efficiently query on that field using dot notation.

db.A.ensureIndex({'_id.orgUnit': 1})

Upvotes: 3

ghik
ghik

Reputation: 10764

These two queries mean two different things.

First one is like: "find me documents whose _id is exactly an object {orgUnit: 1039}". Second one is like: "find me documents whose _id is an object with orgUnit property equal to 1039".

So the second query is weaker and will also match documents like {_id: {foo: "bar", orgUnit: 1039}} while the first query will not. Mongo cannot use index on _id to perform the second query.

Upvotes: 2

Related Questions