How to get the object id in PyMongo after an insert?

后端 未结 6 1136
旧巷少年郎
旧巷少年郎 2020-12-08 13:10

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

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

After the note document is inserte

6条回答
  •  Happy的楠姐
    2020-12-08 14:04

    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
    

提交回复
热议问题