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

时间:2016-04-30 17:45:38

标签: python mongodb mongodb-query pymongo

我需要更新Mongo DB中另一个文档中的数组中的文档。

{
        "_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" : "mxwnnnqafl",
        "tags" : [
                "ab"
        ],
        "title" : "cd"
}

如果我尝试通过下面的命令更新comments数组中的第一个文档,它就可以工作。

db.posts.update({'permalink':"cxzdzjkztkqraoqlgcru"},{'$inc': {"comments.0.num_likes": 1}})

但是如果我在下面的python代码中添加相同的内容,我会收到Write错误,它无法遍历该元素。我不明白缺少什么! 任何人都可以帮帮我。

    post = self.posts.find_one({'permalink': permalink})       
    response = self.posts.update({'permalink': permalink},
                                 {'$inc':"comments.comment_ordinal.num_likes": 1}})

WriteError: cannot use the part (comments of comments.comment_ordinal.num_likes) to traverse the element

2 个答案:

答案 0 :(得分:1)

comment_ordinal 应该是替换,而不是索引本身。你将它视为一个可以映射到序数的整数。我的意思是你应该做的事情:

updated_field = "comments." + str(comment_ordinal) + ".num_likes"

response = self.posts.update({'permalink': permalink}, {'$inc': {updated_field: 1}})

希望这有帮助。

答案 1 :(得分:1)

您做错了,您需要动态构建查询,最好的方法是使用str.format方法。

response = self.posts.update_one(
    {'permalink': permalink},
    {'$inc': {"comments.{}.num_likes".format(comment_ordinal): 1}}
)

此外,如果因为update_one已弃用而需要更新多个文档,则应考虑使用update_many方法进行单次更新和update

相关问题