search

Home  >  Q&A  >  body text

mongodb .查询时间最接近当前时间的10条记录,如何查询

现在有一个需求 ,查询 最新的10记录。
难不成要先排序在取前10条,但是这也太慢了 。

在问下mongodb插入的记录都是在最后吗。那我是不是查询最后10条就可以了 ?
或者该如何查询 最近的10条记录 ?

巴扎黑巴扎黑2871 days ago688

reply all(2)I'll reply

  • 黄舟

    黄舟2017-05-02 09:20:52

    Mongodb defaults to sorting documents in ascending order if no sorting is specified, so it does not meet your needs. You have to first sort to specify -1 for a field, which is descending order, and then limit it to 10

    If you feel it’s slow, add an index

    reply
    0
  • 为情所困

    为情所困2017-05-02 09:20:52

    db.foo.find().sort({_id:1}).limit(10);

    reply
    0
  • Cancelreply