mongodb返回刚插入数据的id用什么方法
PHP中文网
PHP中文网 2017-04-21 11:15:56
0
5
765

在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>

这样应该比较清楚了吧

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(5)
PHPzhong

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

迷茫

_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~

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template