且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

插入后如何在PyMongo中获取对象ID?

更新时间:2022-12-05 17:17:03

关于MongoDB的一件很酷的事情就是ID是在客户端生成的.

One of the cool things about MongoDB is that the ids are generated client side.

这意味着您甚至不必询问服务器ID是什么,因为您首先告诉它要保存什么.使用pymongo,插入的返回值将是对象ID.检查一下:

This means you don't even have to ask the server what the id was, because you told it what to save in the first place. Using pymongo the return value of an insert will be the object id. Check it out:

>>> import pymongo
>>> collection = pymongo.Connection()['test']['tyler']
>>> _id = collection.insert({"name": "tyler"})
>>> print _id
4f0b2f55096f7622f6000000