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

2024-05-29 02:55:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Mongo中做一个简单的插入。。。

db.notes.insert({ title: "title", details: "note details"})

插入note文档后,我需要立即获取对象id。从insert返回的结果有一些关于连接和错误的基本信息,但是没有文档和字段信息。

我找到了一些关于在upsert=true的情况下使用update()函数的信息,我只是不确定这是否是正确的方法,我还没有尝试过。


Tags: 对象文档信息idtruedbtitlemongo
3条回答

泰勒的回答对我不起作用。 使用id。插入的id有效

>>> import pymongo
>>> collection = pymongo.Connection()['test']['tyler']
>>> _id = collection.insert({"name": "tyler"})
>>> print(_id)
<pymongo.results.InsertOneResult object at 0x0A7EABCD>
>>> print(_id.inserted_id)
5acf02400000000968ba447f

较新的PyMongo版本会使insert贬值,而应该使用insert_oneinsert_many。这些函数返回一个pymongo.results.InsertOneResultpymongo.results.InsertManyResult对象。

使用这些对象,您可以分别使用.inserted_id.inserted_ids属性来获取插入的对象id。

有关insert_oneinsert_many和^{this链接。

MongoDB最酷的一点是id是在客户端生成的。

这意味着您甚至不必问服务器id是什么,因为您首先告诉了服务器要保存什么。使用pymongo,insert的返回值将是对象id。请签出:

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

相关问题 更多 >

    热门问题