JAVA下mongo调用

原创 2013年12月04日 15:00:25

项目中要用到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);
	}
}


相关文章推荐

mongo-java-driver-2.7.1.jar

  • 2015年09月26日 23:41
  • 285KB
  • 下载

mongo-java-driver-2.13.0-rc0.jar

  • 2015年01月04日 14:17
  • 589KB
  • 下载

配置mongo java driver显示操作日志

在使用hiberate实现数据层时,总会打开hibernate.show_sql=true选项,显示hibernate生成的SQL语句。他们可以通过生成的SQL语句了解ORM使用和运行,并可以依据SQ...

mongo-java-driver-3.0.rar

  • 2017年04月25日 16:44
  • 1.88MB
  • 下载

mongo-java-driver-3.1.0.jar

  • 2015年11月05日 11:10
  • 1.34MB
  • 下载

mongoDB查询,高级查询,含java操作mongo查询

MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。      MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数...

mongo-java-driver-3.3.0.jar

  • 2016年08月19日 16:01
  • 1.47MB
  • 下载

Mongo Java jar

  • 2016年08月03日 22:32
  • 860KB
  • 下载

java 对 mongo的操作

java拾遗5----Java操作Mongo入门 Java操作Mongo入门 参考: http://api.mongodb.com/java/3.2/ http://www.runoo...

mongo-java-driver-3.4.2.jar

  • 2017年05月02日 12:37
  • 1.6MB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:JAVA下mongo调用
举报原因:
原因补充:

(最多只允许输入30个字)