首先,查找是否存在文档匹配查询。
如果是这样,请使用新数据更新该文档。
否则,将新文档插入数据库。
您可以使用等于 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
设置 upsert=True
完整的测试示例。另请参阅$setOnInsert与$set不同,如果密钥存在,则不会更改记录。
payload= {'id':'key123','other':'stuff'}
collection.update({'eventid':payload['id']}, {"$set": payload}, upsert=True)
collection.count_documents({}) # 1
payload= {'id':'key123','other':'stuff2'}
collection.update({'eventid':payload['id']}, {"$set": payload}, upsert=True)
collection.count_documents({}) # 1
payload= {'id':'key456','other':'more stuff'}
collection.update({'eventid':payload['id']}, {"$setOnInsert": payload}, upsert=True)
collection.count_documents({}) # 2
payload= {'id':'key456','other':'more stuff2'}
collection.update({'eventid':payload['id']}, {"$setOnInsert": payload}, upsert=True)
collection.count_documents({})