【问题标题】:Get index of the last matching element of an array in MongoDB获取MongoDB中数组最后一个匹配元素的索引
【发布时间】:2020-11-02 14:09:06
【问题描述】:

有没有办法获取 MongoDB 中最后一个匹配元素的索引?我说的是相当于 JavaScript 的Array.prototype.lastIndexOf。我知道$indexOfArray,但我正在寻找最后一个索引,而不是第一个。

我的用例

我有一个集合,其架构如下所示:

{
  // ...
  images: [
    {
      identifier: String,
      imageId: ObjectId
    }
  ]
  // ...
}

我有一条记录,其中有重复的元素:

{
  // ...
  images: [
    {
      identifier: '0',
      imageId: ObjectId('objectId0')
    },
    {
      identifier: '1',
      imageId: ObjectId('objectId1')
    },
    {
      identifier: '2',
      imageId: ObjectId('objectId2')
    },
    {
      identifier: '0', // <-- duplicated!
      imageId: ObjectId('objectId3')
    },
    // many more elements...
    {
      identifier: '0', // last occurence
      imageId: ObjectId('objectIdN+0')
    },
    {
      identifier: '1',
      imageId: ObjectId('objectIdN+1')
    },
    {
      identifier: '2',
      imageId: ObjectId('objectIdN+2')
    }
  ]
}

我想删除最后一次出现 images.identifier: '0' 之前的所有元素。

不使用 JavaScript 有可能吗?

【问题讨论】:

  • 您可以使用聚合管道获取所有重复的 IDS,除了最后一个使用 $limit 和 $skip。获得 ID 后,您可以使用 ObjectID 删除它们。
  • @Hiren 但是,我究竟如何获得直到最后一个副本的所有元素数量?我需要将一个非常具体的值传递给$limit
  • 以下是您可以进一步思考的一些想法:Find duplicate urls in mongodb
  • 您要删除“所有在images.identifier: '0' 后面”还是“所有重复的标识符”?

标签: javascript mongodb


【解决方案1】:

试试这个:

db.collection.aggregate([
   {
      $set: {
         images: {
            $reduce: {
               input: "$images",
               initialValue: [],
               in: {
                  $cond: {
                     if: { $eq: ["$$this.identifier", "0"] },
                     then: ["$$this"], // reset array to current value
                     else: { $concatArrays: ["$$value", ["$$this"]] } // append values
                  }
               }
            }
         }
      }
   }
])

【讨论】:

  • 这不会导致重复吗?
  • 不,它没有。它会查找images.identifier: '0',并且删除数组中之前出现的所有内容。我就是这么理解你的要求的。
  • 它确实有效!我不明白如何或为什么?你能不能再详细点?很抱歉给您添麻烦
  • @Wernfriend Docmscheit 没关系,我想我明白了。太棒了,谢谢!
  • 那么$reduce 在我看来并不是那么容易理解:它遍历了数组的每个元素。如果找到identifier: '0',则将数组重置为当前元素。否则,当前元素将附加到数组中。
猜你喜欢
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-26
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
相关资源
最近更新 更多