Configure pymongo to use string _id instead of ObjectId

后端 未结 2 1771
误落风尘
误落风尘 2021-01-03 02:48

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 = studentsR         


        
相关标签:
2条回答
  • 2021-01-03 03:20

    It ended up being fairly simple.

    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.

    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())
    
    0 讨论(0)
  • 2021-01-03 03:33

    in .py files:

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

    it's ok!

    0 讨论(0)
提交回复
热议问题