How to Ignore Duplicate Key Errors Safely Using insert_many

You can deal with this by inspecting the errors produced with BulkWriteError. This is actually an “object” which has several properties. The interesting parts are in details: import pymongo from bson.json_util import dumps from pymongo import MongoClient client = MongoClient() db = client.test collection = db.duptest docs = [{ ‘_id’: 1 }, { ‘_id’: 1 … Read more

Fast or Bulk Upsert in pymongo

Modern releases of pymongo ( greater than 3.x ) wrap bulk operations in a consistent interface that downgrades where the server release does not support bulk operations. This is now consistent in MongoDB officially supported drivers. So the preferred method for coding is to use bulk_write() instead, where you use an UpdateOne other other appropriate … Read more

Authenticate After Picking the Database

You seem to be missing some concepts here so I’ll basically answer as a “guide” to what you should be doing instead. So “authentication’ is not really something you do “after” connection, but rather you need to be “looking in the right place” when you actually attempt to authenticate. We can start this by essentially … Read more

Create an ISODate with pyMongo

You just need to store an instance of datetime.datetime. Inserting from the python shell: >>> c.test.test.insert({‘date’: datetime.datetime.utcnow()}) ObjectId(‘4e8b388367d5bd2de0000000′) >>> c.test.test.find_one() {u’date’: datetime.datetime(2011, 10, 4, 16, 46, 59, 786000), u’_id’: ObjectId(‘4e8b388367d5bd2de0000000’)} Querying in the mongo shell: > db.test.findOne() { “_id” : ObjectId(“4e8b388367d5bd2de0000000”), “date” : ISODate(“2011-10-04T16:46:59.786Z”) }