Get n-th element of an array in MongoDB

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

Leave a Comment