S Andrew
S Andrew

Reputation: 7198

How to insert document in MongoDB with custom object id in Python

I am inserting a document in MongoDB collection using below code:

try:
    x = coll.insert_one(data_dict).inserted_id
    print(x)
except Exception as e:
    log.error("Exception at saving data for db {}".format(cid))
    log.error(e)

This inserts document in collection and mongo db creates its own object id as shown in below image:

enter image description here

_id is automatically created. Is it possible to insert your own id here. How can we do that.

One way of doing this is to create _id in data_dict()

data_dict['_id'] = uuid.uuid4()

and then save the data in db. This then saves the _id with the uuid but the data type is also saved as UUID and I want to save it as ObjectID. Can anyone please help me.

Upvotes: 0

Views: 2088

Answers (1)

jrrysprng02
jrrysprng02

Reputation: 1

Yes you have to make your own objectid with BSON module.

from bson.objectid import ObjectId

Then you can create your own objectid and use it for creation or to insert. This should be a comment but I dont have the required rep.

Upvotes: 1

Related Questions