pymongo嵌入式文档更新

时间:2018-03-24 21:52:15

标签: python mongodb flask pymongo

我在MongoDB 3.6中有以下文档

        forum_collection = { '_id' : id,
                         'tags': tags,
                         'sub_topic_name' : sub_topic_name,
                         'topic_creator' : creator_name,
                         'main_forum_name' : forum_name,
                         'threads' : [ {'thread_id' = uuid4,
                                        'thread_title = title,
                                        'thread_author = author,
                                        'thread_comment_cout = 0,
                                        'thread_body' = content,
                                        'thread_comments' = [ {'thread_comment_id' : uuid4,
                                                               'thread_comment_body': content,
                                                               'thread_commenter' : author,
                                                               'thread_comment_time'   : time
                                                               },
                                                            ]
                                        'thread_time' = time,
                                        },

                                     ],

所以我想让forum_collection有多个sub_topics,每个sub_topics都有线程,每个线程都有注释。

如何添加新的子评论并将thread_comment_count更新为1?我的下面尝试失败了......我的函数传递了三个变量,sub_topic(查询sub_topic_name),thread(查询thread_id)和thread_vals(将新注释附加到thread_id)

forum_collection.find_one_and_update({'sub_topic_name': sub_topic, 'threads.thread_id' : thread},
                                     {'$inc': {'threads.'+thread+'.thread_comments_count': 1},
                                      '$addToSet': {thread + '.threads_comment': thread_vals}},
                                      return_document=pymongo.ReturnDocument.AFTER
                                     )

2 个答案:

答案 0 :(得分:0)

它怎么会失败? 我不知道是否是复制/粘贴错误,但您的" thread_comment_ cout 拼写错误。 另外$ addToSet应该引用" threads"不是"线程"

答案 1 :(得分:0)

我需要在适当的位置添加$ ....所以不是'主题。' + thread +' .thread_comments_count'但是'线程。$。thread_comments_count' ...

forum_collection.find_one_and_update({'sub_topic_name': sub_topic, 'threads.thread_id' : thread},
                                 {'$inc': {'threads.$.thread_comments_count': 1},
                                  '$addToSet': {'threads.$.thread_comments': thread_vals}},
                                  return_document=pymongo.ReturnDocument.AFTER
                                 )