Search code examples
pythonpython-3.xmongodbpymongobson

How to convert string to MongoDB objectId


I have a content like this is my content and I want to store it to the MongoDB collection. The problem is I want to update my data and I want to find the _id of data on the collection without send the query to database. I came up withe the idea to generate my _ids based on the content of my document. I tried to convert the content to the sha256 or ... and then by using the bson.ObjectId in python generate my _id so any time I want to update for example the timestamp in my collection I simply generate the _id and send an update query to the database collection. But I facing an error below:

bson.errors.InvalidId: '3e2550e3ffd205d10900d893dd8d91be9f446d60' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string

I wondering if the idea is wrong or ... Could you please guide me ?


Solution

  • Your idea is fine; the trick is you do not have to use the ObjectId type for the _id field. The following pseudocode works fine where the _id is a String:

    String sid = hex(sha256("this"+"is"+"my"+"content"));
    Document doc = {_id:sid, theTimestamp:ISODate(), ... }
    db.collection.insert(doc);
    ...
    db.collection.update({_id:sid}, {$set: {theTimestamp:ISODate()});