In mongoDB 在文档中也存在的位置获取数组元素

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

我在 node.js 中使用 mongoose 连接 mongodb,现在我有一个文档架构,如下所示

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

现在我想获取 array element 其位置是 counter 也存在于文档中,我读了很多问题,比如在 SO 和其中的大多数上,我发现了 mongoose 聚合,但我不知道如何使用聚合来解决我的问题。

有谁用过聚合请帮帮我

您可以使用以下查询执行此操作:

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

在我的猫鼬中使用这个查询。

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