Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get n-th element of an array in MongoDB

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.

like image 789
mck Avatar asked Aug 28 '11 19:08

mck


People also ask

How do I get an element from an array 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.

How do I query an array field in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }

How do I filter an array of objects in MongoDB?

Filter MongoDB Array Element Using $Filter Operator This operator uses three variables: input – This represents the array that we want to extract. cond – This represents the set of conditions that must be met. as – This optional field contains a name for the variable that represent each element of the input array.

How do I use $in in MongoDB?

MongoDB provides different types of comparison query operators and $in operator is one of them. This operator is used to select those documents where the value of the field is equal to any of the given value in the array.

How to get the nth element of an array in MongoDB?

will retrieve the nth element of the array "my_array" of all documents in the foo collection where bar = "xyz". You can use the $arrayElemAt operator new in MongoDB 3.2 to return the element at the specified array index. The following query return the element at index -2 (second element) in the "fruits" array. For me, this is the Accepted Answer!

How to index comments array in MongoDB?

MongoDB also allows indexing the array elements - in this case, fields of the comment objects of the comments array. For example, if you are querying on the comments by "comments.user" and need fast access, you can create an index for that field. Indexes on array fields are called as Multikey Indexes.

What is the difference between $push and updateone in MongoDB?

The updateOne method updates a document's fields based upon the specified condition. $push is an array update operator which adds an element to an array. If the array doesn't exist, it creates an array field and then adds the element. Let's query the collection and confirm the new comment visually, using the findOne method:

Is it possible to return sub-documents in a MongoDB query?

The MongoDB query language is designed to return all matching Documents. There is no support for returning only sub-documents. This issue has an outstanding ticket in MongoDB's ticket tracker. UPDATE: it looks like the ticket has been marked as fixed.


2 Answers

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

like image 145
Russell Avatar answered Oct 19 '22 19:10

Russell


You can use the $arrayElemAt operator new in MongoDB 3.2 to return the element at the specified array index.


Demo:

A collection named baskets contains documents that look like this:

{
    "_id" : ObjectId("578f326f6db61a299a383c5a"),
    "fruits" : [
        "apple",
        "mango",
        "banana",
        "apricot",
        "cherry"
    ]
}

The following query return the element at index -2 (second element) in the "fruits" array.

db.baskets.aggregate(
    [
        { "$project": { "matched": { "$arrayElemAt": [ "$fruits", 1 ] } } } 
    ] 
)

which produces

{ 
    "_id" : ObjectId("578f326f6db61a299a383c5a"), 
    "matched" : "mango" 
}

And the following query the element before the last element in the array; thus the element at index -2

db.baskets.aggregate(
    [
        { "$project": { "matched": { "$arrayElemAt": [ "$fruits", -2 ] } } } 
    ] 
)

which yields:

{ 
    "_id" : ObjectId("578f326f6db61a299a383c5a"), 
    "matched" : "apricot" 
}
like image 17
styvane Avatar answered Oct 19 '22 18:10

styvane