关闭

JAVA下mongo调用

标签: mongoJAVA
1227人阅读 评论(0) 收藏 举报
分类:

项目中要用到mongo,简单学习了一下,还是挺简单的。

首先下载mongoBD JAR包 https://github.com/mongodb/mongo-java-driver/downloads

调用接口:

import java.util.ArrayList;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.util.JSON;

public class MongoOperator {
	private  String host;
	private  String db_name;
	private  String collection_name;
	
	private Mongo mongo;
	private DB db;
	public DBCollection coll;
	
	
	public MongoOperator(String host, String db, String collection){
		this.host = host;
		this.db_name = db;
		this.collection_name = collection;	
		
		mongo = null;
		db = null;
		coll = null;
	}
	
	public boolean connect() {
		try {
			mongo = new Mongo(host, 27017);
			db = mongo.getDB(db_name);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public DBCollection getDBCollection(){
		coll = null;
		try {
			coll = db.getCollection(collection_name);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return coll;
	}
	
	public String getOneRecord(){
		if(coll != null){
			BasicDBObject obj = (BasicDBObject) coll.findOne();
			return obj.toString();
		}
		return "null";
	}
	
	public boolean insertRecord(String record){
		if(coll != null){
			DBObject dbObject = (DBObject)JSON.parse(record);
			coll.insert(new DBObject[]{dbObject});
			return true;
		}
		return false;
	}
	
	public boolean insertRecord(DBObject record){
		if(coll != null){
			coll.insert(new DBObject[]{record});
			return true;
		}else{
			System.out.println("coll is null");
			return false;
		}
	}
	
	public boolean updateRecord(DBObject record){
		if(coll != null){
			coll.insert(new DBObject[]{record});
			return true;
		}else{
			System.out.println("coll is null");
			return false;
		}
	}
	
	public ArrayList<DBObject> queryRecord(String field, String value){
		ArrayList<DBObject> list = new ArrayList<DBObject>();
		if(coll != null){
			DBObject searchQuery = new BasicDBObject();
            searchQuery.put(field, value);
            DBCursor cursor = coll.find(searchQuery);
            while(cursor.hasNext()) {
            	list.add(cursor.next());
            }
			return list;
		}
		return null;
	}
	
	public int deleteRecord(String field, String value){
		int num = 0;
		ArrayList<DBObject> list = queryRecord(field, value);
		for(DBObject obj:list){
			coll.remove(obj);
			num++;
		}
		return num;
	}
}

一个简单的例子,mongo数据库在远程服务器上,返回的是类似于JSON格式的数据流:

import java.net.UnknownHostException;
import java.util.ArrayList;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
 

public class SimpleTest {
 
	private static String host = "10.13.80.145";
	private static String db_name = "historyNews";//historyNews";webNews;oid2nid
	private static String collection_name = "News";//"News";PageInfo;map
	
	public static void main(String[] args) throws Exception {
		
		MongoOperator mongo = new MongoOperator(host, db_name, collection_name);
		if(mongo.connect()){
			mongo.getDBCollection();
		}

		
		ArrayList<DBObject> list = mongo.queryRecord("_id","12508293");
		for(DBObject obj:list){
			//System.out.println(obj);
			System.out.println(obj.get("content"));
		}
		
	}
}

完整代码:

package mongo;

import java.util.ArrayList;
import java.util.Date;

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

public class Test {
	
	private static String host = "10.13.80.145";
	private static String db_name = "historyNews";//historyNews";webNews;oid2nid
	private static String collection_name = "News";//"News";PageInfo;map
	public static void main(String[] args) throws Exception {
		
		
		
		MongoOperator mongo = new MongoOperator(host, db_name, collection_name);
		if(mongo.connect()){
			mongo.getDBCollection();
			//System.out.println(mongo.getOneRecord());
		}
//		String record = "{\"_id\":\"oid\",\"nid\":\"nid\"}";
//		System.out.println(record);
//		mongo.insertRecord(record);
		
		ArrayList<DBObject> list = mongo.queryRecord("_id","12508293");
		for(DBObject obj:list){
			System.out.println(obj);
			//System.out.println(obj.get("co"));
		}
		
		//mongo.deleteRecord("_id","12861760");
		//Test mt = new Test();
		// mt.insertMemo();
		//mt.getMemo();
		// mt.query();
		// mt.delete();
	}

	public static DBCollection getDBCollection(String collectionName)
			throws Exception {
		Mongo m = new Mongo(host, 27017);
		DB db = m.getDB(db_name);
		System.out.println(db.getName());
		if (db.authenticate("spell", "007".toCharArray())) {
			System.out.println("auth success");
		}
		DBCollection coll = db.getCollection(collectionName);
		if(db.isAuthenticated()){
			System.out.println("isAuthenticated success");
		}
		return coll;
	}

	public void insertMemo() throws Exception {
		DBCollection coll = Test.getDBCollection("memo");
		DBObject doc = new BasicDBObject();
		doc.put("title", "one meeting");
		doc.put("palce", "one meeting");
		doc.put("time", new Date());
		coll.insert(new DBObject[]{doc});
	}

	public void getMemo() throws Exception {
		DBCollection coll = Test.getDBCollection(collection_name);
		BasicDBObject obj = (BasicDBObject) coll.findOne();
		System.out.println(obj);
	}

	public void query() throws Exception {
		DBCollection coll = Test.getDBCollection("memo");
		BasicDBObject obj = new BasicDBObject();
		obj.put("title", "one meeting");
		DBCursor cursor = coll.find(obj);
		while (cursor.hasNext()) {
			Date date = (Date) cursor.next().get("time");
			System.out.println(date.toLocaleString());
		}
		cursor.close();
	}

	public void delete() throws Exception {
		DBCollection coll = Test.getDBCollection("memo");
		BasicDBObject query = new BasicDBObject();
		query.put("title", "one meeting");
		// 找到并且删除,并返回删除的对象
		DBObject removeObj = coll.findAndRemove(query);
		System.out.println(removeObj);
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2022548次
    • 积分:34371
    • 等级:
    • 排名:第132名
    • 原创:1437篇
    • 转载:121篇
    • 译文:19篇
    • 评论:912条
    最新评论