如何使mongodb(pymongo)返回_id作为键值对而不是对象结构? [英] How to have mongodb (pymongo) return _id as key value pair in response instead of object structure?

查看:1040
本文介绍了如何使mongodb(pymongo)返回_id作为键值对而不是对象结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用pymongo烧瓶。
我使用的情况下,我可以将mongodb的文档_id作为整数(从关系存储区迁移的数据)或monogo的ObjectId()(生成)。

在得到的回应中,我分别得到了这样的情况:

第一种情况(带整数id):

  {
_id:123456,
name:something ..
}

ObjectId()的第二种情况

  {
_id:
{
$ oid:55f5efc60640fd09620c109c

:something ..
}

我想要在案例 -
所以我想第二个例子是 -

  {
_id:
name:something ..
} >如何做到这一点? 除了遍历每个结果并替换值外 解决方案

所以可以帮助别人。

在mongo中没有模式,所以你可以把_id的值作为任何东西(整数/对象/字符串,就像我的情况一样)。

在Python中,我做了这个有命令键值对结构:

  from bson.objectid import ObjectId 
new_doc = db.collection.insert({'_ id':str(ObjectId())})//这将不会在您的文档中创建额外的_id字段。

确实如此:

  doc = db.collections.find_one({'_ id':12-char-mongodb-type-id})
doc = db.collections.find_one({'_ id': 12345})


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?

解决方案

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

这篇关于如何使mongodb(pymongo)返回_id作为键值对而不是对象结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆