java操作mongo数据库的实例

MongoDB:Linux下的mongo安装包mongodb-linux-x86_64-3.0.3.tgz

Mongo接口:mongo-java-driver-3.0.3.jar

JSON解析:json.org.jar


实例代码:

package com.learn.test;

//导入json.org.jar中的类
import org.json.JSONException;
import org.json.JSONObject;

//导入mongo-java-driver-3.0.3.jar中的类
import org.bson.Document;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;


public class TestMongo 
{
	public static void main(String[] args) throws JSONException 
	{	 
		//建立与mongo数据库的连接
		MongoClientURI uri=new MongoClientURI("mongodb://10.200.156.7:27017");
        MongoClient client=new MongoClient (uri);

        //读取mongo库内所有的数据库名称
        MongoCursor dbs=client.listDatabaseNames().iterator();
        System.out.println("mongodb中数据库有:");
        while(dbs.hasNext())
        {  
            System.out.println(dbs.next());  
        }  
        
        //读取"hotwords"库中的"url"字段的值
        MongoDatabase db=client.getDatabase("hotwords");  
        MongoCollection collection=db.getCollection("hot_config");  
		MongoCursor cursor=collection.find().iterator();
        System.out.println("mongodb中的hot_config表结果如下:");  
        while(cursor.hasNext())
        {  
        	JSONObject obj=new JSONObject(cursor.next());
            System.out.println("URL:"+obj.getString("url"));  
        }  
        
        //断开与mongo的连接
        client.close();
	}
	
}



你可能感兴趣的:(JAVA)