首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >获取MongoDB中数组的最后一个匹配元素的索引

获取MongoDB中数组的最后一个匹配元素的索引
EN

Stack Overflow用户
提问于 2020-11-02 22:09:07
回答 1查看 43关注 0票数 0

有没有办法获得MongoDB中最后一个匹配元素的索引?我说的是一个与JavaScript的Array.prototype.lastIndexOf等价物。我知道$indexOfArray,但我要找的是最后一个索引,而不是第一个。

我的用例

我有一个集合,它的模式如下:

代码语言:javascript
运行
复制
{
  // ...
  images: [
    {
      identifier: String,
      imageId: ObjectId
    }
  ]
  // ...
}

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

代码语言:javascript
运行
复制
{
  // ...
  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呢?

EN

Stack Overflow用户

回答已采纳

发布于 2020-11-02 23:01:22

试试这个:

代码语言:javascript
运行
复制
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
                  }
               }
            }
         }
      }
   }
])
票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64647116

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档