在mysql中,可以使用last_insert_id()的方法获得最近插入数据的id,但是在mongodb,没找到这样的方法,如何实现呢?
last_insert_id()
def add_post(): post = db.Post() post.title = request.form['title'] post.text = request.form['text'] post.save() return <刚刚插入数据的 _id>
这样应该比较清楚了吧
认证高级PHP讲师
It seems that LZ should be using PyMongo... Then just read post._id and that’s it
post._id
It will update itself after inserting...
def add_post(): post = db.Post() post.title = request.form['title'] post.text = request.form['text'] post.save() return post._id
Reference:
[1] Collection - PyMongo Reference
_id contains timestamp, so it is increasing, just look at the largest one
Maybe LZ means the insertion controlled by yourself, then basically all drivers will return the object just inserted, which contains _id
_id is generally generated by the driver, so theoretically it is already known before insertion.
If using _id use the default objectID, which is saved by your driver and generated before the data is sent to mongo. It should be in the return value of your insert()
If it is Java, after saving or inserting an object in MongoDB, as mentioned above, you can get it by directly removing the attribute ID in the object~
It seems that LZ should be using PyMongo... Then just read
post._id
and that’s itIt will update itself after inserting...
Reference:
[1] Collection - PyMongo Reference
_id contains timestamp, so it is increasing, just look at the largest one
Maybe LZ means the insertion controlled by yourself, then basically all drivers will return the object just inserted, which contains _id
_id is generally generated by the driver, so theoretically it is already known before insertion.
If using _id use the default objectID, which is saved by your driver and generated before the data is sent to mongo. It should be in the return value of your insert()
If it is Java, after saving or inserting an object in MongoDB, as mentioned above, you can get it by directly removing the attribute ID in the object~