【问题标题】:MongoDB - Find array index of document in array fieldMongoDB - 在数组字段中查找文档的数组索引
【发布时间】:2021-08-03 23:07:33
【问题描述】:

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

匹配标准:

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

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

我当前的聚合输出:

{
    '_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,但我仍然很难在我的情况下如何使用它。

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

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

    1. 使用$map 来增加您的records 数组,其中布尔值表示小于20 和大于30
    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
            ]
          }
        }
      }
    ])
    

    Mongo playground

    【讨论】:

    • 感谢您发布解决方案。 lowestCheapestIndex 应该是 1(记录为 _id: 2),因为数组索引以 0 而不是 1 开头。相反,highestExpensiveIndex 应该是最高的索引。这意味着3(记录为_id:4)。感谢代码 sn-p,但它仅显示 below20lowest 数组索引和 over30lowest 数组索引。
    • 答案已更新并附有解释。新解决方案使用$reverseArray
    • 以防万一...您介意编辑您的答案并直接在此处粘贴代码吗?这是因为外部内容有可能在一段时间后被删除。
    猜你喜欢
    • 2017-02-01
    • 2021-06-02
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2017-04-11
    • 1970-01-01
    相关资源
    最近更新 更多