Home > Software design >  Can a mongodb insert contain an expression?
Can a mongodb insert contain an expression?

Time:09-09

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)

CodePudding user response:

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}})

CodePudding user response:

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)

  • Related