Skip to content Skip to sidebar Skip to footer

Objectid Generated By Server On Pymongo

I am using pymongo (python module for mongodb). I want the ObjectID to be created automatically by the server, however it seems to be created by pymongo itself when we don't specif

Solution 1:

If you call save and pass it a document without an _id field, you can force the server to add the _id instead of the client by setting the (enigmatically-named) manipulate option to False:

coll.save({'foo': 'bar'}, manipulate=False)

Solution 2:

I'm not Python user but I'm afraid there's no way to generate _id by server. For performance reasons _id is always generated by driver thus when you insert a document you don't need to do another query to get the _id back.

Here's a possible way you can do it by generating a int sequence _id, just like the IDENTITY ID of SqlServer. To do this, you need to keep a record in you certain collection for example in my project there's a seed, which has only one record:

{_id: ObjectId("..."), seqNo: 1 }

The trick is, you have to use findAndModify to keep the find and modify in the same "transaction".

varidSeed=db.seed.findAndModify({query: {},sort: {seqNo:1},update: { $inc: { seqNo:1 } },new:false});varid=idSeed.seqNo;

This way you'll have all you instances get a unique sequence# and you can use it to sort the records.

Post a Comment for "Objectid Generated By Server On Pymongo"