Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MongoDB how do you index an embedded object fields in an array?

Tags:

mongodb

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?

like image 207
Imran Avatar asked Jan 30 '12 12:01

Imran


People also ask

How do I index an array field in MongoDB?

To index a field that holds an array value, MongoDB creates an index key for each element in the array. These multikey indexes support efficient queries against array fields. Multikey indexes can be constructed over arrays that hold both scalar values [1] (e.g. strings, numbers) and nested documents.

How do I query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

Which index is used to index the content stored in arrays in MongoDB?

MongoDB uses multikey indexes to index the content stored in arrays. If you index a field that holds an array value, MongoDB creates separate index entries for every element of the array. These multikey indexes allow queries to select documents that contain arrays by matching on element or elements of the arrays.


2 Answers

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" }}} )
like image 149
Remon van Vliet Avatar answered Oct 12 '22 22:10

Remon van Vliet


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

db.posts.createIndex({"comments.author" : 1})
like image 29
crifan Avatar answered Oct 12 '22 22:10

crifan