Home:ALL Converter>In mongoDB Fetch array element at a position which is also present in document

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

Ask Time:2016-11-08T00:33:50         Author:Prakash Kumar

Json Formatter

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.

Author:Prakash Kumar,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/40470039/in-mongodb-fetch-array-element-at-a-position-which-is-also-present-in-document
Rohail Najam :

Use this query in my mongoose. \n\nvar aggregation = [\n{\n $project : {\n array : {$arrayElemAt: [ \"$array\", \"$counter\" ] } \n }\n}]\ndb.collectionName.aggregate(aggregation).exec(function(err, model){\nif(err){\n// handle error}\nconsole.log(model);\n})\n",
2016-11-07T16:55:12
yy