Insert MongoDB data when it does not exist and update it when it already exists

  mongodb, question

For example, I now implement the method is to use statements to query:

result = db.collection.find_one(xxxx)
if result:

However, this method is too inefficient. I wonder if there is a better method.

MongoDB introduced a system calledupsertIf no document meets the update criteria, a new document will be created based on the criteria and the updated document. If a matching document is found, it will be updated normally.

For details, seeMongoDB’s documentation.