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?