在 PyMongo 中持久化对象后如何获取对象的 ID?
我有一个 PyMongo 新手问题:如果 collection
是 PyMongo Collection,我用它来保存一个对象,然后
obj = {'foo': 'bar'}
collection.insert(obj)
MongoDB 自动为 obj
生成一个 _id
字段;一旦可以确认这一点,
print obj
就会产生类似的结果
{'foo': 'bar', '_id': ObjectId('4c2fea1d289c7d837e000000')}
我的问题是:如何以我可以使用它的方式获取 _id
?
例如,如果我想从数据库中删除 obj
,我会认为我想做类似的事情
collection.remove(obj['_id'])
,但当我尝试这样做时,我收到消息
TypeError: 'ObjectId' object is unsubscriptable.
发生了什么?
I have a PyMongo newbie question: If collection
is a PyMongo Collection and I use it to save an object with
obj = {'foo': 'bar'}
collection.insert(obj)
then MongoDB automatically generates an _id
field for obj
; once can confirm this with
print obj
which yields something like
{'foo': 'bar', '_id': ObjectId('4c2fea1d289c7d837e000000')}
My question is: How do I get that _id
back out in such a way that I can use it?
For instance, if I want to delete obj
from the database, I would think that I would want to do something like
collection.remove(obj['_id'])
but when I try this I get the message
TypeError: 'ObjectId' object is unsubscriptable.
What's going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您只需要传递
remove
一个字典,就像insert
一样。因此,要根据其_id
值删除文档,请执行以下操作:You just need to pass
remove
a dict, just like you didinsert
. So, to remove a document based on its_id
value, do something like:insert 返回插入文档的_id。
并删除将根据 _id 删除,因此请尝试以下操作:
insert returns the _id of the inserted document.
and remove will remove based on _id, so try something like:
您只需传递 obj 即可。
You can just pass
obj
.要从文档中删除对象,您必须提及条件
因为您可以为文档指定“_id”........
for removing a object from document you have to mention condition
As you can specify "_id" for a document ........