java操作mongodb基础(查询 排序 输出list)
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 );//建立连接
db get_db_credit = mongoclient.getdb("credit_2");//数据库名
dbcollection collection = get_db_credit.getcollection("report");//集合名,对应mysql中的表名
basicdbobject filter_dbobject = new basicdbobject();
//建立查询条件,如果还有其他条件,类似的写即可
// 如:version=3,filter_dbobject.put("version", 3),mongod区分string 和 integer类型,所以要小心"3"!=3
filter_dbobject.put("user_id", "10065716153075");
//下面执行查询,设置limit,只要10条数据,排序(类mysql orderby) 再建一个basicdbobject即可,-1表示倒序
dbcursor cursor = collection.find(filter_dbobject).limit(10).sort(new basicdbobject("create_time",-1));
//把结果集输出成list类型
list<dbobject> list = cursor.toarray();
system.out.println(list.size());//list的长度
system.err.println(cursor.count());//计算结果的数量,类似于(mysql count()函数),不受limit的影响
//遍历结果集
while(cursor.hasnext()) {
system.out.println(cursor.next());
}
}
}