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

后端 未结 6 1124
旧巷少年郎
旧巷少年郎 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条回答
  • 2020-12-08 13:54

    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)
    
    0 讨论(0)
  • 2020-12-08 13:55

    You just need to assigne it to some variable:

    someVar = db.notes.insert({ title: "title", details: "note details"})
    
    0 讨论(0)
  • 2020-12-08 13:58

    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

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-08 14:11

    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
    
    0 讨论(0)
  • 2020-12-08 14:14

    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.

    See this link for more info on insert_one and insert_many and this link for more info on pymongo.results.InsertOneResult.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题