python - 如何在 pymongo (python mongodb) 中执行 get_or_create?

标签 python mongodb pymongo

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

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

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

最佳答案

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

相关文章:

python - 使用 lxml 提取所有元素事先未知的数据

python - 如何在 python 中编辑请求以添加 TLS 设置?

node.js - 在 NodeJS 0.10.8 中安装 Mongoose

mongodb - 如何有条件地在 mongo 中插入文档?

python - 使用 pymongo 调用 ConvertToCapped

python - 我可以使用 Numba、矢量化或多处理加速这种空气动力学计算吗?

python - 使用 for 循环创建多个注释

node.js - Raspberry Pi 2 上的 MongoDb 性能

mongodb - 在 mongoDB 中插入或忽略多个文档

mongodb - 如何在连接字符串中的pymongo mongoclient中提供pemfile密码