如果不存在,MongoDB是插入记录的最快方式吗?

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)

怎么做最快的方式?

Tal*_*dua 5

更新时,使用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

  • 感谢您的回答,但是为什么不回答 stackoverflow 上的任何问题“您应该阅读文档 $url_doc(technology)”?如果我可以在文档中找到问题的答案,我就不会在这里问了。 (2认同)