Get n-th element of an array in MongoDB

前端 未结 3 1249
长情又很酷
长情又很酷 2020-11-30 01:41

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

3条回答
  •  粉色の甜心
    2020-11-30 02:17

    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

提交回复
热议问题