问题
I am using pymongo with flask. I my use case, I can have mongodb's document _id either as integer (migrated data from relational store) or the monogo's ObjectId() (generated).
In get response I get something like this in each case respectively:
1st case (with integer id):
{
"_id": 123456,
"name": "something.."
}
2nd case with ObjectId()
{
"_id":
{
"$oid": "55f5efc60640fd09620c109c"
},
"name": "something.."
}
I want to have uniform structure in both the cases - So I would like the 2nd case to be like -
{
"_id": "55f5efc60640fd09620c109c",
"name": "something.."
}
How to achieve this? Other than iterating through each results and replacing the values?
回答1:
Found solution to my problem, sharing so can help others.
In mongo there is no schema so you can have value of _id as anything (integer/object/string, as in my case).
In python, I did this to have command key-value pair structure:
from bson.objectid import ObjectId
new_doc = db.collection.insert({'_id': str(ObjectId())}) // This won't create additional _id field in your document.
Do find like:
doc = db.collections.find_one({'_id': "12-char-mongodb-type-id"})
doc = db.collections.find_one({'_id': 12345})
来源:https://stackoverflow.com/questions/32555649/how-to-have-mongodb-pymongo-return-id-as-key-value-pair-in-response-instead-o