Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure pymongo to use string _id instead of ObjectId

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.

like image 632
blaineh Avatar asked Jun 10 '14 02:06

blaineh


People also ask

Can MongoDB _id be a string?

Yes, you can use a string as your _id.

Can I use _id from MongoDB?

The _id field is immutable—that is, once a document exists in your MongoDB system, it has, by definition, been assigned an _id, and you cannot change or update its primary key. That said, _id can be overridden when you insert new documents, but by default it will be populated with an ObjectID.

Can we replace _id in MongoDB?

You cannot update it. You'll have to save the document using a new _id , and then remove the old document.

How is _id generated in MongoDB?

By default, MongoDB generates a unique ObjectID identifier that is assigned to the _id field in a new document before writing that document to the database. In many cases the default unique identifiers assigned by MongoDB will meet application requirements.


1 Answers

in .py files:

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

it's ok!

like image 54
qianzui Avatar answered Sep 20 '22 09:09

qianzui