首页 > 解决方案 > 有没有办法将索引数组传递给 mongodb 并从该索引处的数组中获取元素

问题描述

我有一个包含 100 个元素的数组的 mongodb 文档,我想在查询数组中给定的索引处从该数组中获取多个元素。示例:让查询 = [2,3,5,6,7,4,44,32,71]; 所以,我想在查询数组中给出的索引处获取 mongodb doc 中数组中的元素。

标签: javascriptnode.jsmongodbmongoose

解决方案


If you want filter data on mongo side, you can do like this.

db.getCollection('feed').find({
  "_id" : {
    "$in" : [
      ObjectId("55880c251df42d0466919268"), 
      ObjectId("55bf528e69b70ae79be35006")
    ]
  }
});

If not,

const filteredResult = items.filter(item => query.includes(item._id));
console.log(filteredResult);

推荐阅读