How to do get_or_create in pymongo (python mongodb)?

First, find out if a document matching request exists.

If so, update this document with the new data.

Otherwise, insert the new document into the database.

+5
source share
2 answers

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

  • update if it exists.
  • Insert a new one if it does not exist.

From the 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:

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

+9

All Articles