gpt4 book ai didi

Mongodb如何更新数组中的最后一项

转载 作者:行者123 更新时间:2023-12-05 07:23:05 25 4
gpt4 key购买 nike

有人可以告诉我是否可以更新文档数组中的最后一项吗?例如在本文档中:

{
name: 'my name',
someArray: [
{rate: 10},
{rate: 9},
{rate: 20}
]
}

我想将 rate:20 的最后一项更新为 rate: 50。如何准确更新 Mongodb 中的最后一项?谢谢。

最佳答案

一个选项是使用更新管道:

  1. 将数组拆分为最后一项和其余所有项。
  2. 更新最后一项
  3. 使用$concatArrays再次构建数组
db.collection.update(
{name: "my name"},
[
{$set: {
lastItem: {$last: "$someArray"},
rest: {$slice: ["$someArray", 0, {$subtract: [{$size: "$someArray"}, 1]}]}
}
},
{$set: {"lastItem.rate": 50}},
{$set: {
someArray: {$concatArrays: ["$rest", ["$lastItem"]]},
lastItem: "$$REMOVE",
rest: "$$REMOVE"
}
}
])

看看它是如何在 playground example - concatArrays 上工作的

另一种选择是使用 $reduce:

这里我们在数组上迭代,对于每个项目检查它是否是最后一个,如果是则更新它:

db.collection.update(
{name: "my name"},
[
{$set: {lastIndex: {$subtract: [{$size: "$someArray"}, 1]}}},
{$set: {
lastIndex: "$$REMOVE",
someArray: {
$reduce: {
input: "$someArray",
initialValue: [],
in: {
$concatArrays: [
"$$value",
[
{
$cond: [
{$eq: [{$size: "$$value"}, "$lastIndex"]},
{$mergeObjects: [
"$$this",
{rate: 50}
]
},
"$$this"
]
}
]
]
}
}
}
}
}
])

看看它是如何在 playground example - reduce 上工作的

关于Mongodb如何更新数组中的最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56235419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com