MongoDB: obtains the most value of a field in Java.

Source: Internet
Author: User

In Shell operations, we can use Max or min to obtain the maximum value. Or we can use sort and limit to get the most value.

It seems that Max and Min cannot be used in Java, but we can make some modifications to the latter method.

DB. t1.insert ({"_ id": 1, "Hour": 0, "cycletime": 0}) dB. t1.insert ({"_ id": 2, "Hour": 0, "cycletime": 1}) dB. t1.insert ({"_ id": 3, "Hour": 0, "cycletime": 2}) dB. t1.insert ({"_ id": 6, "Hour": 0, "downtime": 6}) dB. t1.insert ({"_ id": 4, "Hour": 0, "cycletime": 3}) dB. t1.insert ({"_ id": 5, "Hour": 1, "cycletime": 4}) dB. t1.insert ({"_ id": 7, "Hour": 1, "downtime": 9 })

The data is as above. If we take the maximum value for hour, we should return the last two documents with the ID of 5, 7.

Basicdbobject keys = new basicdbobject (); keys. put ("Hour",-1); dbcursor cursor = Coll. find (). sort (KEYS ). limit (2); While (cursor. hasnext () {system. out. println (cursor. next (). tostring ());}
Related Article

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.