[英]pymongo embedded document update
我在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,
},
],
所以我想有多个sub_topics,forum_collection,每个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
)
它怎么会失败? 我不知道这是否是复制/粘贴错误,但是您的“ thread_comment_ cout拼写错误。而且$ addToSet应该引用“线程”而不是“线程”
我需要在适当的位置添加$ ....所以不是'threads。'+ thread +'。thread_comments_count'而是'threads。$。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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.