gpt4 book ai didi

arrays - 更新 mongodb 嵌套数组文档中的第 n 个文档

转载 作者:可可西里 更新时间:2023-11-01 09:08:23 24 4
gpt4 key购买 nike

我需要在 Mongodb 的另一个文档中更新数组中的一个文档

    {            "_id" : ObjectId("51cff693d342704b5047e6d8"),            "author" : "test",            "body" : "sdfkj dsfhk asdfjad ",            "comments" : [                    {                            "author" : "test",                            "body" : "sdfkjdj\r\nasdjgkfdfj",                            "email" : "test@tes.com"                    },                    {                            "author" : "hola",                            "body" : "sdfl\r\nhola \r\nwork here"                    }            ],            "date" : ISODate("2013-06-30T09:12:51.629Z"),            "permalink" : "jaiho",            "tags" : [                    "jaiho"            ],            "title" : "JAiHo"    }Q1) Update email of 0th element of comments arraydb.posts.update({"permalink" : "haha"},{$set:{"comments.0.email":1}})This doesn't throw any exception but doesn't update anything as wellQ2) Add a field on nth element of comments array number_likesdb.posts.update({"permalink" : "haha"},{$inc:{"comments.0.num_likes":1}})Doesn't work either.Am I missing something here?

最佳答案

Q1:如果您使用永久链接“jaiho”而不是“haha”进行更新,它肯定会更新电子邮件;

> db.posts.update({"permalink" : "jaiho"},{$set:{"comments.0.email":1}})
> db.posts.find()
..., "email" : 1 },...

Q2:同样适用于此 include;

> db.posts.update({"permalink" : "jaiho"},{$inc:{"comments.0.num_likes":1}})
> db.posts.find()
..., "num_likes" : 1 },...

关于arrays - 更新 mongodb 嵌套数组文档中的第 n 个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17389195/

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