Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a get_or_create in pymongo (python mongodb)?

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.

like image 428
TIMEX Avatar asked Jul 15 '11 06:07

TIMEX


2 Answers

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

like image 114
DhruvPathak Avatar answered Oct 01 '22 12:10

DhruvPathak


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

Set upsert=True

like image 34
Andreas Jung Avatar answered Oct 01 '22 14:10

Andreas Jung