Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can MongoDB use an index when checking for existence of a field with $exists operator?

Tags:

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?

like image 560
bantic Avatar asked Nov 18 '11 00:11

bantic


People also ask

How do I check if a field is indexed in MongoDB?

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.

Why index is not used in MongoDB?

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.

How can you tell if an index was used with a query MongoDB?

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.

Can you create an index on an array field in MongoDB If yes what happens in this case?

MongoDB automatically creates a multikey index if any indexed field is an array; you do not need to explicitly specify the multikey type.


2 Answers

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.

like image 174
RameshVel Avatar answered Sep 19 '22 14:09

RameshVel


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

like image 23
H6. Avatar answered Sep 19 '22 14:09

H6.