How to get the object id in PyMongo after an inser

2019-01-17 14:20发布

I'm doing a simple insert into Mongo...

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

After the note document is inserted, I need to get the object id immediately. The result that comes back from the insert has some basic info regarding connection and errors, but no document and field info.

I found some info about using the update() function with upsert=true, I'm just not sure if that's the right way to go, I have not yet tried it.

4条回答
The star\"
2楼-- · 2019-01-17 14:43

The answer from Tyler does not work for me. Using _id.inserted_id works

>>> 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
查看更多
聊天终结者
3楼-- · 2019-01-17 14:49

One of the cool things about MongoDB is that the ids are generated client side.

This means you don't even have to ask the server what the id was, because you told it what to save in the first place. Using pymongo the return value of an insert will be the object id. Check it out:

>>> import pymongo
>>> collection = pymongo.Connection()['test']['tyler']
>>> _id = collection.insert({"name": "tyler"})
>>> print _id
4f0b2f55096f7622f6000000
查看更多
甜甜的少女心
4楼-- · 2019-01-17 14:57

You just need to assigne it to some variable:

someVar = db.notes.insert({ title: "title", details: "note details"})
查看更多
Explosion°爆炸
5楼-- · 2019-01-17 15:00

updated; removed previous because it wasn't correct

It looks like you can also do it with db.notes.save(...), which returns the _id after it performs the insert.

See for more info: http://api.mongodb.org/python/current/api/pymongo/collection.html

查看更多
登录 后发表回答