gpt4 book ai didi

mongodb - 如何将序数位置传递到 Pymongo 中的更新文档中以进行 $inc 更新

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

我有一个文档,其中包含没有 ID 的嵌套文档数组

_id: adsjfdsau7Hukad,
'nested':[{ a:'123456',b:'zzzzzzzzz'},
{a:'788123',b:'6yuuuuuu'},
{a:'123456',b:'ooo998uj'}]

我想在已识别文档的指定元素中增加一个新属性“c”。例如:

db.collection.update({_id:'adsjfdsau7Hukad'},{$inc:{'nested.2.c':1}})

当我可以显式编写元素序号位置标识符时,此方法有效。但是,我需要为元素序号位置传递一个变量,但我还没有找到这样做的方法。我试过这个:

var num = 4 ## as example
db.collection.update({_id:'adsjfdsau7Hukad','nested.$': num},{$inc:{'nested.$.c':1}})

但这似乎不起作用。

有什么想法吗?

最佳答案

您需要以编程方式生成 key :

在外壳中:

var num = 4;
var inc = {};
inc['nested.' + num + '.c'] = 1;
db.collection.update({_id: 'adsjfdsau7Hukad'}, {$inc: inc})

在 pymongo 中:

num = 4
db.collection.update(
{'_id': 'adsjfdsau7Hukad'},
{'$inc': {'nested.' + str(num) + '.c': 1}})

关于mongodb - 如何将序数位置传递到 Pymongo 中的更新文档中以进行 $inc 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18068656/

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