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

use*_*472 39 insert mongodb pymongo

我正在做一个简单的插入Mongo ...

db.notes.insert({ title: "title", details: "note details"})
Run Code Online (Sandbox Code Playgroud)

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

我发现了一些关于使用upsert = true的update()函数的信息,我只是不确定这是否是正确的方法,我还没有尝试过.

Tyl*_*ock 78

关于MongoDB的一个很酷的事情是,id是客户端生成的.

这意味着您甚至不必询问服务器ID是什么,因为您首先告诉它要保存什么.使用pymongo,insert的返回值将是object id.看看这个:

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

  • 这需要标记为正确.谢谢! (4认同)
  • 在现代版本中,我们应该使用 .inserted_id 属性。https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one https://api.mongodb.com/python/current/api/pymongo/collection.html #pymongo.collection.Collection.insert_one (3认同)
  • 好的答案,尽管我建议使用`_id`或`id_`作为名称。我在python中不使用`id`,但是不使用内置函数名可能是一个好习惯。 (2认同)

Kum*_*abh 20

泰勒的答案对我不起作用.使用_id.inserted_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
Run Code Online (Sandbox Code Playgroud)


Meh*_*chi 14

最好使用 insert_one() 或 insert_many() 而不是 insert()。这两个是针对较新版本的。您可以使用 insert_id 来获取 id。

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
myDB = myclient["myDB"]
userTable = myDB["Users"]
userDict={"name": "tyler"}

_id = userTable.insert_one(userDict).inserted_id
print(_id)
Run Code Online (Sandbox Code Playgroud)

或者

result = userTable.insert_one(userDict)
print(result.inserted_id)
print(result.acknowledged)
Run Code Online (Sandbox Code Playgroud)

如果你需要使用insert(),你应该像下面这样写

_id = userTable.insert(userDict)
print(_id)
Run Code Online (Sandbox Code Playgroud)


Jur*_*dom 5

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

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

请参阅链接上的更多信息insert_one,并insert_many链接的更多信息pymongo.results.InsertOneResult


Eve*_*man 2

更新; 删除了之前的内容,因为它不正确

看起来你也可以用 来做到这一点db.notes.save(...),它在执行插入后返回 _id 。

有关更多信息,请参阅: http://api.mongodb.org/python/current/api/pymongo/collection.html