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

80 Views Asked by At

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.

2

There are 2 best solutions below

1
Rohail Najam On BEST ANSWER

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);
})
0
felix On

you can do this with this query:

db.pos.aggregate([
   {
      $project:{
         result:{
            $arrayElemAt:[
               "$array",
               "$counter"
            ]
         }
      }
   }
])