6

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

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

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

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.

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.

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.

Community
  • 1
  • 1
blaineh
  • 2,263
  • 3
  • 28
  • 46

2 Answers2

6

in .py files:

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

it's ok!

qianzui
  • 61
  • 1
  • 1
  • This is working... adding the _id to the dict, force mongo to use that _id and not the default ObjectId() – Izack Jun 18 '17 at 18:40
4

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())
blaineh
  • 2,263
  • 3
  • 28
  • 46
  • 1
    It appears that add_son_manipulator() is now deprecated. I'm having trouble finding a suitable alternative. Does anyone have any ideas? It doesn't seem to be working in Python 2.7.10 anyway. I added a breakpoint and a print statement inside of the transform_incoming() method the code never reaches that point. – John Carrell Feb 02 '16 at 15:19