Amit Beckenstein
Amit Beckenstein

Reputation: 1332

Get index of the last matching element of an array in MongoDB

Is there a way to get the index of the last matching element in MongoDB? I'm speaking of an equivalent to JavaScript's Array.prototype.lastIndexOf. I know about $indexOfArray, but I'm looking for the last index, not the first one.

My use case

I've got a collection whose schema looks like this:

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

I have a record whose got duplicated elements:

{
  // ...
  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')
    }
  ]
}

I want to remove all the elements before the last occurence of images.identifier: '0'.

Is it possible at all without the usage of JavaScript?

Upvotes: 0

Views: 174

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59652

Try this one:

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
                  }
               }
            }
         }
      }
   }
])

Upvotes: 1

Related Questions