gpt4 book ai didi

mongodb - 插入到 mongo 数组的特定索引

转载 作者:IT老高 更新时间:2023-10-28 13:13:20 26 4
gpt4 key购买 nike

Mongo 支持文档中的文档数组。例如,像

{_id: 10, "coll": [1, 2, 3] }

现在,假设我想在任意索引处插入任意值

{_id: 10, "coll": [1, {name: 'new val'}, 2, 3] }

我知道您可以使用 $ 和 $set 更新适当的值,但不能用于插入。仅仅为了在特定索引处插入就必须替换整个数组,这有点糟糕。

最佳答案

2.6 版 开始,您终于可以做到这一点了。您必须使用 $position运算符(operator)。对于您的特定示例:

db.students.update(
{ _id: 10},
{ $push: {
coll: {
$each: [ {name: 'new val'} ],
$position: 1
}
}}
)

关于mongodb - 插入到 mongo 数组的特定索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6415173/

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