How do I update a Mongo document after inserting it?

后端 未结 5 598
借酒劲吻你
借酒劲吻你 2020-12-04 13:57

Let\'s say I insert the document.

post = { some dictionary }
mongo_id = mycollection.insert(post)

Now, let\'s say I want to add a field and

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 14:58

    mycollection.find_one_and_update({"_id": mongo_id}, 
                                     {"$set": {"newfield": "abc"}})
    

    should work splendidly for you. If there is no document of id mongo_id, it will fail, unless you also use upsert=True. This returns the old document by default. To get the new one, pass return_document=ReturnDocument.AFTER. All parameters are described in the API.

    The method was introduced for MongoDB 3.0. It was extended for 3.2, 3.4, and 3.6.

提交回复
热议问题