38

The mongodb documentation for multikeys gives an example of querying embedded object fields in an array:

http://www.mongodb.org/display/DOCS/Multikeys

But there's no explanation on how you create an index for that situation. Creating an index on the array doesn't seem to work (using the explain mechanism you can see the index isn't use).

Additional details:

> // find posts where julie commented
> db.posts.find( { "comments.author" : "julie" } )
{"title" : "How the west was won", 
 "comments" : [{"text" : "great!" , "author" : "sam"},
               {"text" : "ok" , "author" : "julie"}],
 "_id" : "497ce79f1ca9ca6d3efca325"}

If you do db.articles.ensureIndex( { comments : 1 } ) it won't index the subfields of the comments objects but rather only the comments object itself.

So the following would use the index:

 > db.posts.find( {comments : { "author" : "julie", "text" : "ok" } } )

Because it's search on the comments objects

But the following wouldn't use the index:

 > db.posts.find( { "comments.author" : "julie" } )

So how do you get mongodb to index for the second case?

2
  • Care to show some code on how you are doing things? Commented Jan 30, 2012 at 12:04
  • As far as I can tell, it does tell you how to add this index: db.articles.ensureIndex( { tags : 1 } ). Commented Jan 30, 2012 at 12:04

3 Answers 3

54

You can create the following index :

db.posts.ensureIndex({"comments.author" : 1})

This will index only the author field of the embedded documents. Note that the index will be used for

db.posts.find( { "comments.author" : "julie" } )

As well as

db.posts.find( { comments: {$elemMatch: {author : "julie" }}} )
Sign up to request clarification or add additional context in comments.

2 Comments

Yes. I think the key point here that the OP and the other answer missed is that the index is dot seperated and contained in double quotes.
@jdi If I were to find a comment on a post and then run createIndex({"author": 1}) on it would that give the same result as runing db.posts.ensureIndex({"comments.author" : 1})?
2

now is 2021 year. according to latest Mongodb official doc, should use createIndex

db.posts.createIndex({"comments.author" : 1})

Comments

-2

you create the index as if you would with a "normal" field;

db.[collection].ensureIndex( { [yourArrayField] : 1 } )

2 Comments

That will only index the objects in the array and not the fields on the objects, I've added some extra details into the question to demonstrate.
If the array contains simple string instead of complex object, @japrescott is correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.