ObjectID generated by server on pymongo

一个人想着一个人 提交于 2019-12-11 01:37:54

问题


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 specify it.

The problem it raises is that I use ObjectID to sort by time (by just sorting by the _id field). However it seems that it is using the time set on each computer so we cannot truly rely on it. Any idea on how to solve this problem?


回答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)



回答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".

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

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



来源:https://stackoverflow.com/questions/24111937/objectid-generated-by-server-on-pymongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!