How to get the object id in PyMongo after an inser

2019-01-17 14:25发布

问题:

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.

回答1:

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


回答2:

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:

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



回答4:

You just need to assigne it to some variable:

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