Java operation mongodb base of of query sort output list

  • 2020-04-01 02:39:41
  • OfStack


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");//The database name
        DBCollection collection = get_db_credit.getCollection("report");//The collection name corresponds to the table name in mysql
        BasicDBObject filter_dbobject = new BasicDBObject();

        //Set up a query condition, if there are other conditions, similar to write
        //For example :version=3,filter_dbobject. Put ("version", 3),mongod distinguishes between String and Integer, so be careful with "3"! = 3
        filter_dbobject.put("user_id", "10065716153075");

        //Now I'm going to do the query, I'm going to set limit, I'm going to do 10 pieces of data, I'm going to do the sort (mysql Derby) and I'm going to do a BasicDBObject, -1 is the reverse order
        DBCursor cursor = collection.find(filter_dbobject).limit(10).sort(new BasicDBObject("create_time",-1));

        //Output the result set as a list type
        List<DBObject> list = cursor.toArray();
        System.out.println(list.size());//The length of the list
        System.err.println(cursor.count());//The number of calculated results, similar to the (mysql count() function), is not affected by limit

        
        //Traversing the result set
        while(cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    }
}


Related articles: