首页 > 解决方案 > MongoDB - 在数组字段中查找文档的数组索引

问题描述

我有包含数组字段的聚合。该数组字段包含文档(对象)。对于这些,我有一些匹配条件,我想创建一个名为lowestCheapIndexand的新字段highestExpensiveIndex,每个字段都有匹配元素的数组索引。

匹配标准:

lowestCheapIndex- 应包含价格低于 20 的任何记录项的最低数组索引号。

highestExpensiveIndex- 应包含价格超过 30 的任何记录项的最高数组索引号。

我当前的聚合输出:

{
    '_id': 'Egg shop',
    'records': [
        {'_id': 1, 'price': 22},
        {'_id': 2, 'price': 18},
        {'_id': 3, 'price': 34},
        {'_id': 4, 'price': 31},
        {'_id': 5, 'price': 13},
    ]
}

期望的输出:

{
    '_id': 'Egg shop',
    'records': [
        {'_id': 1, 'price': 22},
        {'_id': 2, 'price': 18},
        {'_id': 3, 'price': 34},
        {'_id': 4, 'price': 31},
        {'_id': 5, 'price': 13},
    ],
    'lowestCheapIndex': 1,
    'highestExpensiveIndex': 3,
}

问题:

如何根据我的条件检索数组索引?我$indexOfArray在文档中找到了,但我仍然很难在我的情况下如何使用它。

标签: mongodbmongodb-query

解决方案


您可以在聚合管道中执行以下操作:

  1. 用于使用指示低于 20 和超过 30 的布尔值$map来扩充您的数组records
  2. 用于$indexOfArray搜索布尔值;对于highestExpensiveIndex,首先反转数组以获得索引,然后从数组的大小中减去它 - 1 以获得预期的索引。
db.collection.aggregate([
  {
    "$addFields": {
      "records": {
        "$map": {
          "input": "$records",
          "as": "r",
          "in": {
            "_id": "$$r._id",
            "price": "$$r.price",
            "below20": {
              $lt: [
                "$$r.price",
                20
              ]
            },
            "over30": {
              $gt: [
                "$$r.price",
                30
              ]
            }
          }
        }
      }
    }
  },
  {
    "$addFields": {
      "lowestCheapIndex": {
        "$indexOfArray": [
          "$records.below20",
          true
        ]
      },
      "highestExpensiveIndex": {
        "$subtract": [
          {
            "$subtract": [
              {
                $size: "$records"
              },
              {
                "$indexOfArray": [
                  {
                    "$reverseArray": "$records.over30"
                  },
                  true
                ]
              }
            ]
          },
          1
        ]
      }
    }
  }
])

蒙古游乐场


推荐阅读