7

首先,查找是否存在文档匹配查询。

如果是这样,请使用新数据更新该文档。

否则,将新文档插入数据库。

4

3 回答 3

14

您可以使用等于 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

于 2011-07-15T06:21:21.913 回答
2

http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update

设置 upsert=True

于 2011-07-15T06:21:38.673 回答
0

完整的测试示例。另请参阅$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({})
于 2020-01-17T21:48:02.063 回答