首先,查找是否存在文档匹配查询。
如果是,请使用新数据更新该文档。
否则,将新文档插入数据库。
最佳答案
您可以使用等于 true 的“upsert”。 然后,您以“upsert”为 true 运行的更新查询将完全符合您的要求。
- 如果存在则更新。
- 如果不存在则插入新的。
来自 MongoDb 文档:
db.collection.update( criteria, objNew, upsert, multi )
Arguments:
criteria - query which selects the record to update;
objNew - updated object or $ operators (e.g., $inc) which manipulate the object
upsert - if this should be an "upsert"; that is, if the record does not exist, insert it
multi - if all documents matching criteria should be updated
http://www.mongodb.org/display/DOCS/Updating
例子:
db.test.update({"x": "42"}, {"$set": {"a": "21"}},True)
#True => Upsert is True
在此处查看“更新”文档:
http://api.mongodb.org/python/current/api/pymongo/collection.html
关于python - 如何在 pymongo (python mongodb) 中执行 get_or_create?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6703330/