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

后端 未结 6 1134
旧巷少年郎
旧巷少年郎 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)
    

提交回复
热议问题