michael nesterenko
michael nesterenko

Reputation: 14439

select custom array element by index from document field

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?

Upvotes: 1

Views: 419

Answers (1)

Sede
Sede

Reputation: 61225

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 ] } ]

Upvotes: 1

Related Questions