search

Home  >  Q&A  >  body text

mongodb返回刚插入数据的id用什么方法

在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中文网2809 days ago786

reply all(5)I'll reply

  • PHPz

    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

    reply
    0
  • 迷茫

    迷茫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

    reply
    0
  • 黄舟

    黄舟2017-04-21 11:17:56

    _id is generally generated by the driver, so theoretically it is already known before insertion.

    reply
    0
  • 阿神

    阿神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()

    reply
    0
  • 伊谢尔伦

    伊谢尔伦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~

    reply
    0
  • Cancelreply