Search code examples
node.jsmongodbmongoosemongodb-aggregation

In mongoDB Fetch array element at a position which is also present in document


I am using mongoose for connecting mongodb in node.js, now i have a document schema as given below

var ArraySchema = new Schema({
     array: [{type: String}],
     counter: {type: 'Number', required: true}
});

Now i want to fetch array element whose position is counter which is present in the document as well, i read many questions like this on SO and on most of them i found mongoose aggregation but i don't know how to use aggregation to solve my problem.

If anyone of you have used aggregation please help me.


Solution

  • Use this query in my mongoose.

    var aggregation = [
    {
      $project : {
        array :  {$arrayElemAt: [ "$array", "$counter" ] }  
        }
    }]
    db.collectionName.aggregate(aggregation).exec(function(err, model){
    if(err){
    // handle error}
    console.log(model);
    })