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

时间:2013-06-30 10:02:42

标签: arrays mongodb updates

我需要在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 array
db.posts.update({"permalink" : "haha"},{$set:{"comments.0.email":1}})
This doesn't throw any exception but doesn't update anything as well
Q2) Add a field on nth element of comments array number_likes
db.posts.update({"permalink" : "haha"},{$inc:{"comments.0.num_likes":1}})
Doesn't work either.

Am I missing something here?

2 个答案:

答案 0 :(得分:6)

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

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

Q2:同样适用于此;

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

答案 1 :(得分:4)

如果您尝试在Node JS中动态执行此操作,则应该可以正常工作。

i = 0;
selector = {};
operator = {};
selector['comments.' + i + '.email'] = 1; // {'comments.0.num_likes' : 1}
operator['$inc'] = selector;  // {'$inc' : {'comments.0.num_likes' : 1} }
db.posts.update({'permalink' : 'xyz'}, operator);