I have following document in 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,
},
],
SO I want to have forum_collection with multiple sub_topics, each sub_topics have threads and each thread have comments.
How can I add a new sub comment and update the thread_comment_count to 1 ? My following attempt fails miserably...my function passes three variables, sub_topic (to query the sub_topic_name), thread (to query thread_id) and thread_vals (to append new comment to 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
)
How does it fail? I don't know if it was a copy/paste error but your "thread_comment_ cout is misspelled . Also the $addToSet should refer to "threads" not "thread"
I needed to add $ at appropriate places....so not 'threads.'+thread+'.thread_comments_count' but '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
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.