在 PyMongo 中持久化对象后如何获取对象的 ID?

发布于 2024-09-06 23:40:03 字数 739 浏览 15 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

天煞孤星 2024-09-13 23:40:03

您只需要传递remove一个字典,就像insert一样。因此,要根据其 _id 值删除文档,请执行以下操作:

collection.remove({'_id': ObjectId('4c2fea1d289c7d837e000000')})

You just need to pass remove a dict, just like you did insert. So, to remove a document based on its _id value, do something like:

collection.remove({'_id': ObjectId('4c2fea1d289c7d837e000000')})
放肆 2024-09-13 23:40:03

insert 返回插入文档的_id。

并删除将根据 _id 删除,因此请尝试以下操作:

doc_id = db.test.insert({"foo": 1})
db.test.remove(doc_id)

insert returns the _id of the inserted document.

and remove will remove based on _id, so try something like:

doc_id = db.test.insert({"foo": 1})
db.test.remove(doc_id)
荒路情人 2024-09-13 23:40:03

您只需传递 obj 即可。

You can just pass obj.

坦然微笑 2024-09-13 23:40:03

要从文档中删除对象,您必须提及条件
因为您可以为文档指定“_id”........

_id = db.test.insert({"foo": "test"})
db.test.remove({"_id":_id})

for removing a object from document you have to mention condition
As you can specify "_id" for a document ........

_id = db.test.insert({"foo": "test"})
db.test.remove({"_id":_id})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文