MongoDB数据不存在时插入,已存在时更新
天蓬老师
天蓬老师 2017-04-21 11:15:38
0
3
650

如题,我现在实现的方法是用语句来查询:

result = db.collection.find_one(xxxx)
if result:
    更新数据
else:
    插入数据

但是,这种方法效率太低了,不知道有没有更好的方法?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
小葫芦

MongoDB introduces a special update called upsert. If no document meets the update conditions, a new document will be created based on this condition and the updated document; if a matching document is found, it will be updated normally.

See MongoDB’s documentation for details.

刘奇

upsert:
db.collection.update(xx, xx,true)
Just set the third parameter to true

刘奇

I don’t know if anyone has tested mongodb’s find_one. There is no problem when querying billions of data (tested).

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template