在mysql中,可以使用last_insert_id()
的方法获得最近插入数据的id,但是在mongodb,没找到这样的方法,如何实现呢?
def add_post(): post = db.Post() post.title = request.form['title'] post.text = request.form['text'] post.save() return <刚刚插入数据的 _id>
这样应该比较清楚了吧
PHPz2017-04-21 11:17:56
It seems that LZ should be using PyMongo... Then just read post._id
and that’s it
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
迷茫2017-04-21 11:17:56
_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
黄舟2017-04-21 11:17:56
_id is generally generated by the driver, so theoretically it is already known before insertion.
阿神2017-04-21 11:17:56
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()
伊谢尔伦2017-04-21 11:17:56
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~