Ins*_*ing 0 python mongodb nosql mongodb-query
我想在MongoDB数据库中插入一条记录,但前提是它还不存在.有些东西告诉我这个代码在性能方面不是最佳的:
if db.foo.find(record).count() == 0:
db.foo.insert(record)
Run Code Online (Sandbox Code Playgroud)
怎么做最快的方式?
更新时,使用upsert标志:
db.foo.update_one(filter, updates_dict, upsert=True)
Run Code Online (Sandbox Code Playgroud)
工作例子:
db.things.update_one({'thing':'apple'}, {'$set':{'color':'red'}}, upsert=True)
Run Code Online (Sandbox Code Playgroud)
这将搜索firts文档'thing': 'apple'并将其颜色更新为红色.如果没有找到文档,它将创建一个包含这两个参数的文档.
请参阅文档:http://api.mongodb.org/python/current/index.html
| 归档时间: |
|
| 查看次数: |
3053 次 |
| 最近记录: |