有没有办法获得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呢?
发布于 2020-11-02 23:01:22
试试这个:
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
}
}
}
}
}
}
])
https://stackoverflow.com/questions/64647116
复制相似问题