If I have data in my users collection that looks like:
{ name: '...',
email: '...',
...,
photos: {
123: { url: '...', title: '...', ... },
456: { url: '...', title: '...', ... },
...
}
}
And I want to find which user owns photo id 127, then I am using the query:
db.users.find( {'photos.127': {'$exists' => true} } );
I’ve tried, but it doesn’t seem possible to get MongoDB to use an index for this query. The index I tried was: db.users.ensureIndex({photos:1});. And when I used explain() mongo told me it was using a BasicCursor (i.e., no index was used).
Is it possible to create an index that mongo will use for this query?
Updated:
Seems
$existsqueries use index properly now based on these tickets$exists queries should use index & {$exists: false} will not use index
Old Answer:
No, there is no way to tell mongodb to use index for exists query. Indexing is completely related to data. Since $exists is only related to the keys (fields) it cant be used in indexes.
$exists just verifies whether the given key (or field) exists in the document.