vkt
vkt

Reputation: 1459

Remove BSON Object ID when querying mongo DB using pymongo

I'm using Pymongo and flask to build a rest API, and the documents are stored in the following BSON format:

{'_id': ObjectId('123'), 'title':"test"}

how can I query the Mongo DB to get the document in the following format or convert the query result to the following format?

{'_id':'123', 'title':"test"}

Upvotes: 1

Views: 2473

Answers (2)

Bryce Wayne
Bryce Wayne

Reputation: 351

I am assuming that you wish to rename the _id of the document in the collection. You can do this by querying the database collection then replacing the document in the collection.

myquery = {'title':"test"}
# _ = col.find(myquery)
# To check if it exists
y = db['my collection'].update_one(myquery, {"$set": {'_id': '123'}})

Hope it helps. If you give me more info about database and collection I could help more.

Upvotes: 1

Gustavo Bezerra
Gustavo Bezerra

Reputation: 11064

You can apply str to your ObjectId:

item = {'_id': ObjectId('123'), 'title':"test"}
item['_id'] = str(item['_id'])

Upvotes: 4

Related Questions