1

Ho can I select specific array element by index defined in document?

For example I have following document:

{ "_id" : 1, "idx" : 1, "vals" : [ 1, 2 ] }

And I want to select vals element defined by idx index.

I have managed to select specific array element defined by literal:

> db.test.find({_id:1}, {vals:{$slice:[1, 1]}})
{ "_id" : 1, "idx" : 1, "vals" : [ 2 ] }

But how can I use idx field in $slice operator?

0

1 Answer 1

1

The optimal way to do this is in MongoDB 3.2 using the $arrayElemAt operator:

db.test.aggregate([  
    { "$project": { "vals": { "$arrayElemAt": [ "$vals", "$idx" ] } } }
])

You can also use findOne if you use _id in your query criteria and to get idx value.

var idx = db.test.findOne({ "_id": 1 }).idx
db.test.find({ "_id": 1 }, { "vals": { "$slice": [ idx, 1 ]}})

With find you need to use cursor.map

db.test.find().map(function(doc) { 
    doc.vals = doc.vals.slice(doc.idx, 2); 
    return doc; 
})

Result:

[ { "_id" : 1, "asd" : 1, "vals" : [ 2 ] } ]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.