MongoDB学习系列8:连接mongodb进行查询处理

package main;


//import
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;


import java.net.UnknownHostException;


//当前类用于XXX
//JAVA驱动下载地址 https://github.com/mongodb/mongo-java-driver/releases
//JAVA驱动版本 2.11.3 



public class GetUserShareThings {

private static final String outServer       = "127.0.0.1" ;
private static final int      outPort          = 28000                  ;
private static final String  outDataBase  = "tuijian"                        ;
private static final String  outCollection  = "sharings"                       ;

private static void output(String s) {
System.out.println(s);
}
public static void main(String[] args)  throws UnknownHostException {
long index = 0 ;

System.out.println("程序开始执行12....");

Mongo conn  	   = new Mongo( outServer , outPort );
//Mongo conn  	   = new Mongo( );
DB        db          = conn.getDB( outDataBase ) ;
DBCollection   dc = db.getCollection( outCollection ) ;
DBCursor       cursor = null;
BasicDBObject       singleRecord = null ;
//BasicDBObject  document = new BasicDBObject();
BasicDBObject  ref =new BasicDBObject();
BasicDBObject  fields =new BasicDBObject();
BasicDBObject  sort = new BasicDBObject();
////////////////////////////////////
String s ="";
String _id = "";
String XXX = "";
int  cat =0;
String name ="";
String position = "";


long        tc           = dc.getCount();
System.out.println("分享总数:"+tc);



///构造查询的字段
fields.put(  "_id", 1 );
fields.put( "XXX" , 1 ) ;
fields.put( "cat" ,  1 );
fields.put( "n" ,  1 );
fields.put( "p" ,  1 );

//构造排序字段
sort.put( "XXX" ,  1 ) ;
output("------------------------------------------------------------------");
        

cursor =  dc.find( ref, fields).sort(sort);

if(cursor == null) {
output("!!! cursor is null\n");
} else {
output(" big con,the cursor is not null...") ;
}

while(null != cursor && cursor.hasNext() ) {
output("@@@@@@");
//表明有数据
singleRecord = (BasicDBObject) cursor.next() ;
if( null == singleRecord) {
continue;
}
//取到了数据对象
//可以进行操作了
_id = singleRecord.getString("_id");
XXX= singleRecord.getString("XXX");
cat = singleRecord.getInt("cat");
name = singleRecord.getString("n");
position = singleRecord.getString("p");
index++;
s ="" +  index  +"     " + _id  + "  "+ XXX + "  " + cat + "   " + name + "   " + position ; 
output(s);
/*
try {
Thread.sleep(1000);
} catch(Exception e) {
break;
}
*/


}


if( null!= cursor ) {
cursor.close();
}

if( null != dc ) {
dc = null ;
}
if( null != db) {
db = null ;
}
if ( null != conn ) {
conn.close() ;
}
System.out.println("程序结束执行...");

}

}



执行结果如下:(意思意思就行了)

30914     4534508  100007063323  4    360卫士   /data/app/com.qihoo360.mobilesafe-2.apk
@@@@@@
3430915     45345309  10000706453  4   快牙三国跳跳   /data/app/com.dxp.sangojump-1.apk
@@@@@@
30916     45344310  100003  4   土豆电视剧动漫视频播放器   /data/app/com.tudou.android-2.apk



你可能感兴趣的:(mongodb)