skip to Main Content

I need to insert a mongodb document with a field id equal to the string representation of _id (historic reasons, don’t ask). Short of specifying my own _id, is there any way to do it in one call?

This inserts a field that’s a literal "$_id".

from pymongo import MongoClient
...
user = { "name": "ccc", "address": "Highway 37", "id": "$_id" }
result = db.users.insert_one(user)

2

Answers


  1. I think the issue is that MongoDB assigns the _id after the query gets evaluated so you can try something like that:

    from pymongo import MongoClient
    from bson.objectid import ObjectId
    
    ...
    user = { "name": "ccc", "address": "Highway 37"}
    result = db.users.insert_one(user)
    # get the _id to insert it again
    _id = result.inserted_id
    db.users.update_one({'_id': ObjectId(_id)},{"$set": {"id": _id}})
    
    Login or Signup to reply.
  2. You can generate the _id yourself instead of letting mongo do it

    from bson.objectid import ObjectId
    
    _id = ObjectId()
    user = {"_id": _id, "name": "ccc", "address": "Highway 37", "id": _id }
    result = db.users.insert_one(user)
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search