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?
Finding indexes You can find all the available indexes in a MongoDB collection by using the getIndexes method. This will return all the indexes in a specific collection. Result: The output contains the default _id index and the user-created index student name index.
Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement.
In MongoDB, you can use the cursor. explain() method or the db. collection. explain() method to determine whether or not a query uses an index.
MongoDB automatically creates a multikey index if any indexed field is an array; you do not need to explicitly specify the multikey type.
Updated:
Seems $exists
queries 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.
Since MongoDB 2.0 $exists
queries should use an index. Unfortunately this fix has disappeared in the newest version and will be fixed in MongoDB 2.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With