How to have mongodb (pymongo) return _id as key value pair in response instead of object structure?

大兔子大兔子 提交于 2019-12-13 06:34:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!