配置pymongo使用字符串_id而不是ObjectId

时间:2014-06-10 02:09:30

标签: mongodb meteor pymongo

我使用pymongo使用来自其他系统的旧信息为数据库播种,我有很多这样的查询:

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

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

我想配置pymongo以生成_id作为字符串而不打扰ObjectId&#39>

我使用Meteor规范创建的任何对象都将使用字符串格式,而不是ObjectId格式。我不希望在我的应用程序中混合使用id类型,因为它导致了我的互操作性问题。

我知道我可以create ObjectId's from Meteor,但坦率地说,我更倾向于使用字符串格式。它是Meteor的默认设置,它更加简单,I can't find any good reason to use ObjectId's in my particular app

The valueOf() mongo function或类似的东西可以解析_id并在数据库中用于更新文档,但是更直接的东西会更好。

2 个答案:

答案 0 :(得分:5)

<。>在.py文件中:

from bson.objectid import ObjectId
......
kvdict['_id'] = str(ObjectId())
......
mongoCollection.insert(kvdict)

没关系!

答案 1 :(得分:3)

结果很简单。

son_manipulator module可用于将传入的文档更改为其他形式。大部分时间this is used to encode custom objects,但它也适用于此。

有了操纵器,进行转换只需要calling the str() function on the ObjectId

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())
相关问题