如何在pymongo中实现get_or_create?

8 投票
3 回答
7694 浏览
提问于 2025-04-16 21:35

首先,检查一下有没有符合查询条件的文档。

如果有,就用新的数据更新这个文档。

如果没有,就在数据库里插入一个新的文档。

3 个回答

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({})
14

你可以把“upsert”设置为真。这样你执行的更新查询就会完全按照你的想法来。

  • 如果存在,就更新。
  • 如果不存在,就插入新的。

这是来自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

撰写回答