MongoDb 数组更新

发布于 2024-12-12 23:16:10 字数 589 浏览 0 评论 0原文

我正在尝试更新 Mongodb 中的以下文档。

    doc = { id : 10 , graph :[{userId:1,children:[2]},{userId:2,children:[]}]}

    db.test.insert(doc)

然后我执行两次更新:(

db.test.update( {'id':10,'graph.userId' : 1}, { $push:{'graph.$.children':10}})

db.test.update( {'id':10,'graph.userId' : 1},{ $push:{'graph':{'userId':10,'children':[]}}})

遗憾的是:

db.test.update( {'id':10,'graph.userId' : 1},{ $push:{'graph.$.children':10},$push:{'graph':{'userId':10,'children':[]}}})

不起作用)

有没有办法同时更新这些?

多谢

I am trying to update the following document in Mongodb.

    doc = { id : 10 , graph :[{userId:1,children:[2]},{userId:2,children:[]}]}

    db.test.insert(doc)

then I perform two updates:

db.test.update( {'id':10,'graph.userId' : 1}, { $push:{'graph.$.children':10}})

db.test.update( {'id':10,'graph.userId' : 1},{ $push:{'graph':{'userId':10,'children':[]}}})

(Saddly :

db.test.update( {'id':10,'graph.userId' : 1},{ $push:{'graph.$.children':10},$push:{'graph':{'userId':10,'children':[]}}})

does not work)

Is there a way to update these simultaneously ?

Thanks a lot

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

つ可否回来 2024-12-19 23:17:43

修饰符数组中的多个键使其无法工作。如果我正确地阅读了您的 shema,您必须执行两次更新才能执行此操作,因为您正在尝试将新子项推到当前位置并将新记录推到父项的子文档中。

阻止它的是 Children[] 设置。 Mongo 只是不知道在哪里设置。

我想你可以尝试:

db.test.update( {'id':10,'graph.userId' : 1},{ $push:{'graph.$.children':10},$pushAll:{'graph':{{'userId':10,'children':[]}}}})

但这可能性不大

The multiple keys in the modifier array stop it from working. You have to do two updates to do this if I read your shema right cos you are trying to push a new child onto the current position and push a new record into the subdocument of the parent.

The thing that stops it is the children[] setting. Mongo just does not know where to set that.

I suppose you could try:

db.test.update( {'id':10,'graph.userId' : 1},{ $push:{'graph.$.children':10},$pushAll:{'graph':{{'userId':10,'children':[]}}}})

But it is a long shot

孤单情人 2024-12-19 23:17:12

您可以将多个更新操作捆绑在一起,但您用伪代码编写的唯一问题是您要推送的元素属于不同的数组(分别是 graph 和 graph.children。)这需要在两次推送中完成。

试试这个:

db.test.update( { id:10, 'graph.userId':1 }, 
        { $push:{'graph.$.children' : 4 }, $push:{'graph' : {'userId':4,'children':[]}} } )

You can bundle multiple update operations together, but the only issue with what you've written in pseudo code is that the elements you're pushing belong to different arrays (graph and graph.children respectively.) This needs to be done in two pushes.

Try this:

db.test.update( { id:10, 'graph.userId':1 }, 
        { $push:{'graph.$.children' : 4 }, $push:{'graph' : {'userId':4,'children':[]}} } )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文