61

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.

Eliran Malka
  • 15,821
  • 6
  • 77
  • 100
user1125472
  • 611
  • 1
  • 5
  • 3

8 Answers8

99

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.inserted_id 
4f0b2f55096f7622f6000000
Tyler Brock
  • 29,626
  • 15
  • 79
  • 79
  • 3
    Good answer, though I'd suggest the use of `_id` or `id_` as the name. I don't use `id` much in python, but it's probably a good habit not to use built-in function names. – beardc Feb 23 '13 at 05:03
  • 3
    In modern versions we should use .inserted_id attribute. 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 – stepuncius Feb 06 '20 at 11:46
46

The answer from Tyler does not work for me.

Using inserted_id works

>>> import pymongo
>>> collection = pymongo.Connection()['test']['tyler']
>>> db_result = collection.insert({"name": "tyler"})
>>> print(db_result)
<pymongo.results.InsertOneResult object at 0x0A7EABCD>
>>> print(db_result.inserted_id)
5acf02400000000968ba447f
Chris
  • 4,009
  • 3
  • 21
  • 52
Kumar Saurabh
  • 711
  • 7
  • 7
19

It's better to use insert_one() or insert_many() instead of insert(). Those two are for the newer version. You can use inserted_id to get the 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)

Or

result = userTable.insert_one(userDict)
print(result.inserted_id)
print(result.acknowledged)

If you need to use insert(), you should write like the lines below

_id = userTable.insert(userDict)
print(_id)
Mehdi Hasirchi
  • 236
  • 2
  • 5
13

Newer PyMongo versions depreciate insert, and instead insert_one or insert_many should be used. These functions return a pymongo.results.InsertOneResult or pymongo.results.InsertManyResult object.

With these objects you can use the .inserted_id and .inserted_ids properties respectively to get the inserted object ids.

Find out more about insert_one, insert_many, and pymongo.results.InsertOneResult at the pymongo docs.

icedwater
  • 4,701
  • 3
  • 35
  • 50
Jurgen Strydom
  • 3,540
  • 1
  • 23
  • 30
2

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

Eve Freeman
  • 32,467
  • 4
  • 86
  • 101
  • Sorry, was a bit confused by pymongo--updated answer which should work. – Eve Freeman Jan 09 '12 at 04:34
  • 1
    Note that save(D) is actually a driver-side convenience method for either insert(D) or update(D._id, D) depending on whether or not D has an _id field (insert if it doesn't, update if it does) – Remon van Vliet Jan 09 '12 at 12:52
1
some_var = db.notes.insert({ title: "title", details: "note details"})
print(some_var.inserted_id)
Galahad
  • 21
  • 3
0

You just need to assigne it to some variable:

someVar = db.notes.insert({ title: "title", details: "note details"})
hestellezg
  • 3,309
  • 3
  • 33
  • 37
0

To get the ID after an Insert in Python, just do like this:

doc = db.notes.insert({ title: "title", details: "note details"})
return str(doc.inserted_id) # This is to convert the ObjectID (type of doc.inserted_id into string)
Quok
  • 1
  • 2