8

First, find if a document matching query exists.

If so, update that document with the new data.

Otherwise, insert a new document into the database.

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • 1
    Possible duplicate of [MongoDB: Insert if not exists](http://stackoverflow.com/questions/2801008/mongodb-insert-if-not-exists)? – Jim Dennis Jul 15 '11 at 06:38
  • not homework but unable to read basic documentation.... –  Jul 15 '11 at 07:08

3 Answers3

14

You can use "upsert" equal to true. Then the update query you run with "upsert" as true will do exactly what you want.

  • update if exists.
  • insert new if it does not exist.

From MongoDb documentation:

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

Example:

db.test.update({"x": "42"}, {"$set": {"a": "21"}},True)    
#True => Upsert is True

See "update" documentation here :

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

DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
0

Full test example. Also see $setOnInsert which unlike $set will not alter the record if the key exists.

payload= {'id':'key123','other':'stuff'}
collection.update({'eventid':payload['id']}, {"$set": payload}, upsert=True)
collection.count_documents({}) # 1

payload= {'id':'key123','other':'stuff2'}
collection.update({'eventid':payload['id']}, {"$set": payload}, upsert=True)
collection.count_documents({}) # 1

payload= {'id':'key456','other':'more stuff'}
collection.update({'eventid':payload['id']}, {"$setOnInsert": payload}, upsert=True)
collection.count_documents({}) # 2

payload= {'id':'key456','other':'more stuff2'}
collection.update({'eventid':payload['id']}, {"$setOnInsert": payload}, upsert=True)
collection.count_documents({})
citynorman
  • 4,918
  • 3
  • 38
  • 39