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 ());
}
}
}