配置pymongo以使用字符串_id代替ObjectId [英] Configure pymongo to use string _id instead of ObjectId

查看:1083
本文介绍了配置pymongo以使用字符串_id代替ObjectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用pymongo用来自不同系统的旧信息为数据库播种,并且我有很多这样的查询:

I'm using pymongo to seed a database with old information from a different system, and I have a lot of queries like this:

studentId = studentsRemote.insert({'price': price})

在实际的python脚本中,studentId打印为字符串,但是在我正在使用此数据的javascript Meteor应用程序中,它在任何地方都显示为ObjectId(...).

In the actual python script, that studentId prints as a string, but in the javascript Meteor application I'm using this data in, it shows up everywhere as ObjectId(...).

我想配置pymongo以将_id生成为字符串,而不用担心ObjectId的问题

I want to configure pymongo to generate the _id as a string and not bother with ObjectId's

我用Meteor规范创建的任何对象都将使用字符串格式,而不是ObjectId格式.我不想在我的应用程序中混用id类型,因为这引起了我的互操作性难题.

Any objects I create with the Meteor specification will use the string format, and not the ObjectId format. I don't want to have mixing of id types in my application, because it's causing me interoperability headaches.

我知道我可以从流星创建ObjectId ,但坦率地说,我宁愿使用字符串格式.这是Meteor的默认设置,它更简单,并且我找不到任何在我的特定应用中使用ObjectId的充分理由..

I'm aware I can create ObjectId's from Meteor but frankly I'd much rather use the string format. It's the Meteor default, it's much simpler, and I can't find any good reason to use ObjectId's in my particular app.

valueOf() mongo函数或类似的东西解析_id并在文档进入数据库后用于更新文档,但是更直接的东西会很好.

The valueOf() mongo function or something similar could parse the _id and be used to update the document once it's in the database, but it would be nice to have something more direct.

推荐答案

它最终变得非常简单.

son_manipulator模块可用于更改传入文档以其他形式.在大多数情况下,这用于对自定义对象进行编码,但它确实有效也为此.

The son_manipulator module can be used to change incoming documents to a different form. Most of the time this is used to encode custom objects, but it worked for this as well.

有了操纵器,只需调用在对象ID上使用str()函数进行转换.

With the manipulator in place, it was just a matter of calling the str() function on the ObjectId to make the transformation.

from pymongo.son_manipulator import SONManipulator
class ObjectIdManipulator(SONManipulator):
    def transform_incoming(self, son, collection):
        son[u'_id'] = str(son[u'_id'])      
        return son

db.add_son_manipulator(ObjectIdManipulator())

这篇关于配置pymongo以使用字符串_id代替ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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