2024-05-29 02:55:36 发布
网友
我在Mongo中做一个简单的插入。。。
db.notes.insert({ title: "title", details: "note details"})
插入note文档后,我需要立即获取对象id。从insert返回的结果有一些关于连接和错误的基本信息,但是没有文档和字段信息。
我找到了一些关于在upsert=true的情况下使用update()函数的信息,我只是不确定这是否是正确的方法,我还没有尝试过。
泰勒的回答对我不起作用。 使用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_one或insert_many。这些函数返回一个pymongo.results.InsertOneResult或pymongo.results.InsertManyResult对象。
insert
insert_one
insert_many
pymongo.results.InsertOneResult
pymongo.results.InsertManyResult
使用这些对象,您可以分别使用.inserted_id和.inserted_ids属性来获取插入的对象id。
.inserted_id
.inserted_ids
有关insert_one、insert_many和^{this链接。
MongoDB最酷的一点是id是在客户端生成的。
这意味着您甚至不必问服务器id是什么,因为您首先告诉了服务器要保存什么。使用pymongo,insert的返回值将是对象id。请签出:
>>> import pymongo >>> collection = pymongo.Connection()['test']['tyler'] >>> _id = collection.insert({"name": "tyler"}) >>> print _id 4f0b2f55096f7622f6000000
泰勒的回答对我不起作用。 使用id。插入的id有效
较新的PyMongo版本会使
insert
贬值,而应该使用insert_one
或insert_many
。这些函数返回一个pymongo.results.InsertOneResult
或pymongo.results.InsertManyResult
对象。使用这些对象,您可以分别使用
.inserted_id
和.inserted_ids
属性来获取插入的对象id。有关this链接。
insert_one
、insert_many
和^{MongoDB最酷的一点是id是在客户端生成的。
这意味着您甚至不必问服务器id是什么,因为您首先告诉了服务器要保存什么。使用pymongo,insert的返回值将是对象id。请签出:
相关问题 更多 >
编程相关推荐