Get n-th element of an array in MongoDB

mck picture mck · Aug 28, 2011 · Viewed 41.9k times · Source

As part of my document in MongoDB I'm storing an array of objects. How can I query it for only the 4th element of the array for example? So I don't want the get the entire array out, just the 4th element.

Answer

Russell picture Russell · Aug 28, 2011

Use $slice.

db.foo.find({ bar : "xyz" } , { my_array : { $slice : [n , 1] } } )

will retrieve the nth element of the array "my_array" of all documents in the foo collection where bar = "xyz".

Some other examples from the MongoDB documentation:

db.posts.find({}, {comments:{$slice: 5}}) // first 5 comments
db.posts.find({}, {comments:{$slice: -5}}) // last 5 comments
db.posts.find({}, {comments:{$slice: [20, 10]}}) // skip 20, limit 10
db.posts.find({}, {comments:{$slice: [-20, 10]}}) // 20 from end, limit 10

Which you can read here: http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields