2011-07-15 45 views
5

首先,查找是否存在匹配查詢的文檔。如何在pymongo(python mongodb)中執行get_or_create?

如果是這樣,請用新數據更新該文檔。

否則,在數據庫中插入一個新文檔。

+0

是有些功課? ; x – ThiefMaster

+0

[MongoDB:插入如果不存在]可能的重複(http://stackoverflow.com/questions/2801008/mongodb-insert-if-not-exists)? –

+0

沒有作業,但無法讀取基本文檔.... –

回答

9

你可以使用「upsert」等於true。 然後,將「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 

請參閱 「Update」 文件位置:

http://api.mongodb.org/python/current/api/pymongo/collection.html

+1

'update'只返回一個'WriteResult'。改爲使用findAndModify。 – mljli

相關問題