配置 pymongo 使用字符串 _id 而不是 ObjectId [英] Configure pymongo to use string _id instead of ObjectId

查看:60
本文介绍了配置 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.

我知道我可以从 Meteor 创建 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.

操纵器就位后,只需调用str() 函数对 ObjectId 进行转换.

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天全站免登陆