首页 > 解决方案 > 查询 MongoDB 数组中的多个索引

问题描述

我想查询 MongoDB 文档中数组的一些特定的非连续索引。
我考虑过的选项是:

  1. 查询整个数组,然后在客户端脚本中按索引过滤。这是不可行的,因为对于大型数组,它将导致从数据库中获取不需要的项目(假设我只需要索引 5 和 20,但实际上数组中有 1000 个项目)。
  2. 每次我想从数组中选择每个索引时,多次使用 $slice。但这会导致 N 次调用。
  3. 我可以使用子架构代替简单的数组,其中数组中的每个项目都有一个分配的 ID,并且在查询时,我可以使用“查找”来选择那些特定的 ID。但这增加了一个我不想要的额外“id”字段。我确信必须有一种方法可以通过数组索引来选择项目。

我正在寻找一种更优雅的解决方案,我可以在一次操作中从数组中选择某些特定的索引。

测验模型中的示例文档:

{
     questions: [
          {
               text: "Question 1",
               answer: "Answer 1",
          },
          {
               text: "Question 2",
               answer: "Answer 2",
          },
          ...
          ...
          {
               text: "Question 1000",
               answer: "Answer 1000",
          },
     ]
}

我想要以下内容:

const questions = await Quiz.find({
     questions: {
          $index_in: [10, 42, 66]
     }
}).exec();

预期输出:

[
     {
          text: "Question 10",
          answer: "Answer 10",
     },
     {
          text: "Question 42",
          answer: "Answer 42",
     },
     {
          text: "Question 66",
          answer: "Answer 66",
     },

标签: mongodbmongoose

解决方案


如果要从数组中获取特定索引

测试代码在这里

询问

代替

  • [0,2,5] 带有您想要的索引(或数组的驱动程序变量)
  • 而不是"$myarray",输入您的字段名称(在您的情况下"$questions"

$arrayElemAt它的速度很快,因为O(1)

db.collection.aggregate([
  {
    "$addFields": {
      "myarray": {
        "$map": {
          "input": [
            0,
            2,
            5
          ],
          "as": "i",
          "in": {
            "$arrayElemAt": [
              "$myarray",
              "$$i"
            ]
          }
        }
      }
    }
  }
])

推荐阅读