如何在mongodb中将数组插入到embeded文档中

时间:2016-01-07 09:22:53

标签: python mongodb mongodb-query pymongo

我有这样的文件:

b = { "_id":"10001", "comments":[{"comid":"3","comtime":"2014","author":"jenny"}]}

我想插入另一个像:

c = {"comid":"34","comtime":"2015","author":"jack"}

进入comid,其值为“3”。 我想要的结果是:

{
        "_id" : "10001",
        "comments" : [
                {
                        "comid" : "3",
                        "comtime" : "2014",
                        "author" : "jenny",
                        "replycomment" : [
                                {
                                        "comid" : "34",
                                        "comtime" : "2015",
                                        "author" : "jack"
                                }
                        ]
                }
        ]
}

我想在数组中有另一个嵌入文档来回复评论。

任何想法?

1 个答案:

答案 0 :(得分:0)

您需要使用update_one方法和$push更新运算符。

replycomment = {"comid": "34", "comtime": "2015", "author": "jack"}
collection.update_one(
    {"comments.comid": "3"}, 
    {"$push": {"comments.$.replycomment": replycomment}}
)