Java Operations MongoDB Base (query sort output list) _java

Source: Internet
Author: User
Tags mongoclient mongodb

Copy Code code as follows:

Package com.infomorrow.webroot;

Import java.util.List;

Import Com.mongodb.BasicDBObject;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import Com.mongodb.DBObject;
Import com.mongodb.MongoClient;

public class Test_mongodb {
public static void Main (String args[]) throws Exception {
Mongoclient mongoclient = new Mongoclient ("127.0.0.1", 27017);//Establish a connection
DB Get_db_credit = Mongoclient.getdb ("credit_2");//Database name
Dbcollection collection = Get_db_credit.getcollection ("the")//collection name, corresponding to the table name in MySQL
Basicdbobject filter_dbobject = new Basicdbobject ();

Create query conditions, if there are other conditions, similar write can
For example: Version=3,filter_dbobject.put ("Version", 3), Mongod distinguish between string and integer types, so be careful "3"!=3
Filter_dbobject.put ("user_id", "10065716153075");

The following execution query, set limit, as long as 10 data, sorting (class MySQL by order) and then build a basicdbobject,-1 for reverse
dbcursor cursor = Collection.find (filter_dbobject). Limit. Sort (new Basicdbobject ("Create_time",-1));

Output the result set to the list type
list<dbobject> list = Cursor.toarray ();
System.out.println (List.size ()); Length of//list
System.err.println (Cursor.count ())//The number of results calculated, similar to (MySQL count () function), unaffected by limit


Traverse result set
while (Cursor.hasnext ()) {
System.out.println (Cursor.next ());
}
}
}

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.