1

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"}
1

2 Answers 2

4

You can apply str to your ObjectId:

item = {'_id': ObjectId('123'), 'title':"test"}
item['_id'] = str(item['_id'])
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply, yes I ended up doing this, was wondering if there any better way to achieve this using BSON API?
You can change the type used by the document through the MongoClient constructor document_class parameter (defaults to dict), but I am not aware of any way to change the serialization of a specific field.
1

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.

3 Comments

Hi Bryce, thanks for the reply. No, I don't want to update the database, I need to convert the document to a proper JSON format when sending the result via rest API {'_id':'123', 'title':"test"}
Ah, ok. Well, this will replace your ObjectID('123') to '123'
Yes, I don't want to make changes to Database. I want to keep the data in BSON format in the mongo but want to convert that to above-expected format when sending to the client.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.