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

时间:2020-11-02 14:09:06

标签: javascript mongodb

有没有办法获取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完全有可能吗?

1 个答案:

答案 0 :(得分:1)

尝试这个:

for i in range(6):
    for j in range(12):
        ax = axes[i,j] # these are the axes created via plt.subplots(6,12,...)
        ax.axis('off')
        # … your other code here