Search code examples
python-3.xmongodbobjectid

Is it possible to update MongoDB String field with a String that is an ObjectId in Python


So I have a String array field in MongoDB collection that I would like to add a String that is an ObjectId. It gets added but gets saved as an ObjectId instead of a String.

                users_collection.update_one({
                    "_id": ObjectId(user['_id'])
                }, {
                    "$push": {
                        "profile.surveys.completedInTimeSurveyIDs": "5dc71ee34283e125a9edc96b"
                    }
                })

Which always saves in the collection document as:

enter image description here

But I want it to be:

enter image description here


Solution

  • Likely you have defined a schema in your framework and your framework know that the type of the value referred by your path (here profile.surveys.completedInTimeSurveyIDs.$ would have been specified as oid and thus your string is cast as so)

    Alternatives are:

    • design your schema according to your spec (as a string)
    • bypass the framework and directly use the driver (if exceptional and possible)
    • consider really storing an ObjectId and adapt your code upon retrieval (str() if needed)

    I would advise you to do the latter (if you were to aggregate stuff, lookup, even populate, or any other work involving your array element, you are likely to need an ObjectId)