【问题标题】:Configure pymongo to use string _id instead of ObjectId将 pymongo 配置为使用字符串 _id 而不是 ObjectId
【发布时间】:2014-07-30 16:09:22
【问题描述】:

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

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

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

我想将pymongo 配置为将_id 生成为字符串,而不是使用ObjectId 的

我使用 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 并在文档进入数据库后用于更新它,但如果有更直接的东西会更好。

【问题讨论】:

    标签: mongodb meteor pymongo


    【解决方案1】:

    在 .py 文件中:

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

    没关系!

    【讨论】:

    • 这是有效的...将 _id 添加到字典中,强制 mongo 使用该 _id 而不是默认的 ObjectId()
    【解决方案2】:

    它最终变得相当简单。

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

    【讨论】:

    • 看来 add_son_manipulator() 现在已弃用。我很难找到合适的替代品。有没有人有任何想法?无论如何,它似乎不适用于 Python 2.7.10。我在 transform_incoming() 方法中添加了一个断点和一个打印语句,代码永远不会到达那个点。
    猜你喜欢
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2015-12-13
    • 2021-03-18
    • 2012-03-18
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多