Search code examples
mongodbpymongobson

PyMongo inserting BSON document to MongoDB


I would like to insert a new document into my MongoDB collection.

My first input is a string that is shown here:

{
    "date" : ISODate("2013-10-06T18:11:26.329Z"),
    "engines" : {},
    "expiration_date" : ISODate("2013-10-06T18:11:36.329Z"),
    "file_name" : "elad.elad",
    "scan_status" : "TEST",
    "task_id" : "4ce4ae9e-ef0a-476a-8189-92a5bfe328bd"
}

I'm creating a bson.BSON object with this string:

b=bson.BSON(doc)

I'm trying to insert it into my collection in MongoDB:

collection.insert(b)

but I get the following error: TypeError: 'str' object does not support item assignment

Does someone know what is the problem here?


Solution

  • You can directly convert string to BSON, you either require json.loads or BSON.encode method.

    You can use following code :

    import datetime
    from pymongo import MongoClient
    
    db = MongoClient().test
    collection = db.some
    
    doc = {
        "date" : datetime.datetime.strptime("2013-10-06T18:11:26.329Z", "%Y-%m-%dT%H:%M:%S.%fz"),
        "engines" : {},
        "expiration_date" : datetime.datetime.strptime("2013-10-06T18:11:36.329Z","%Y-%m-%dT%H:%M:%S.%fz"),
        "file_name" : "elad.elad",
        "scan_status" : "TEST",
        "task_id" : "4ce4ae9e-ef0a-476a-8189-92a5bfe328bd"
    }
    collection.insert(doc)
    

    Here I am using datetime object to convert your string date to Python compatible datetime