Last document inserted by mongodb

Source: Internet
Author: User
When using Mongodb, we need to obtain the last record of a set. at the beginning, we wanted to sort by _ id, but this should not be strictly ordered. we also tried the timestamp method, which cannot solve our problem. in the end, we can't use the redi... when using Mongodb, we need Obtains the last record of a set..
At the beginning, we wanted to pass _idSorting, but this should not be strictly ordered.
We also tried the timestamp method, which cannot solve our problem.
In the end, we can't use it. redis generates an auto-increment id and stores it in mongodb.
However, this usage is really disgusting. Do you have any good solutions to this problem?

Reply content:

When using Mongodb, we needObtains the last record of a set..
At the beginning, we wanted to pass_idSorting, but this should not be strictly ordered.
We also tried the timestamp method, which cannot solve our problem.
In the end, we can't use it. redis generates an auto-increment id and stores it in mongodb.
However, this usage is really disgusting. Do you have any good solutions to this problem?

_ Id is enough. The generation is related to the time.

ObjectId is a 12-byte BSON type, constructed using:

A 4-byte value representing the seconds since the Unix epoch,
A 3-byte machine identifier,
A 2-byte process id, and
A 3-byte counter, starting with a random value

If you do not have an algorithm for writing _ id, you can use _ id to sort the data directly.

Unless you have created your own Mongodb ObjectId, _ id is the unique primary key. You can obtain the last data by sorting the data below.

 $sort:{_id:-1 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.