java简单操作mongodb

MongoDB 的文档(document),相当于关系数据库中的一行记录
● 多个文档组成一个集合(collection),相当于关系数据库的表。多个集合(collection),逻辑上组织在一起,就是数据库(database)
●一个 MongoDB 实例支持多个数据库(database)
● 默认端口: 27017
下面是使用java对MongoDB 进行的简单操作
添加java链接数据库jar包 
mongo-java-driver-2.9.3.jar
 
<pre class="java" name="code">package test;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bson.types.ObjectId;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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.MongoException;
import com.mongodb.QueryOperators;
import com.mongodb.util.JSON;

public class MongoTest {
	private Mongo mg = null;
	private DB db;
	private DBCollection things;

	@Before
	public void init() {
		try {
			mg = new Mongo();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
		db = mg.getDB("things");
		things = db.getCollection("things");
	}

	@After
	public void destory() {
		if (mg != null)
			mg.close();
		mg = null;
		db = null;
		things = null;
		System.gc();
	}

	public void print(Object o) {
		System.out.println(o);
	}

	/**
	 * <b>function</b>查询所有数据
	 * 
	 * @author jiangjie
	 * @createDate 2015-1-28
	 */

	private void queryAll() {
		print("查询things所有的数据");
		DBCursor cur = things.find();
		while (cur.hasNext()) {
			print(cur.next());
		}
	}
	@Test
	public void findAll() {
		queryAll();
	}
	/**
	 * 添加数据
	 */
	@Test
	public void add() {
		// 查询所有数据
//		queryAll();
//		print("count:" + things.count());
		DBObject thing = new BasicDBObject();
		thing.put("name", "jiangjie");
		thing.put("age", 24);
		thing.put("sex", "男");
//		// 获取影响行数
//		print(things.save(thing).getN());
//		//添加多条数据,传递Array对象
//		print(things.insert(new BasicDBObject("name","tom")).getN());
		//添加List集合
		List<DBObject> list=new ArrayList<DBObject>();
		list.add(thing);
		DBObject thing1=new BasicDBObject("name","lucy");
		thing1.put("age", 22);
		list.add(thing1);
		//添加
		print(things.insert(list).getN());
		//查询下数据,看看是否添加成功
		print("count:"+things.count());
		things.insert(new BasicDBObject("_id",3.0));
		queryAll();
	}
	/**
	 * 删除数据
	 */
	@Test
	public void remove(){
		queryAll();
		print("删除id=54c876eb28e05e10b97ba2db: "+things.remove(new BasicDBObject("_id", new ObjectId("54c876eb28e05e10b97ba2db"))).getN());
	}
	/**
	 * 修改数据
	 */
	@Test
	public void  modify(){
		/*print("修改:"+things.update(new BasicDBObject("_id", new ObjectId("54c8582028e0fcf222a595fb")),new BasicDBObject("name", "123")).getN());
	    print("修改:"+things.update(
	    		 new BasicDBObject("_id", new ObjectId("54c8582028e0fcf222a595fb")),
	    		 new BasicDBObject("name", "123456"),
	    		 true,//如果数据库不存在,是否添加
	    		 false//多条修改
	    		 ).getN());
	    print("修改:"+things.update(
	    		 new BasicDBObject("_id", new ObjectId("54c8582028e0fcf222a595fb")),
	    		 new BasicDBObject("name", "1234567"),
	    		 true,//如果数据库不存在,是否添加
	    		 true//false只修改一条,true如果有多条就不修改
	    		 ).getN());*/
		
	   //当数据库不存在不修改,不添加数据,当多条数据就修改
	/*   print("修改:"+things.update(
	    		 new BasicDBObject("_id", new ObjectId("54c8582028e0fcf222a595fb")),
	    		 new BasicDBObject("name", "1234567")
	    		 ).getN());
	  */
		things.update(new BasicDBObject("_id",new ObjectId("54c859e228e0d222fbb7ac04")), new BasicDBObject("$set",new BasicDBObject("name", "aaaa")));
	}
	/**
	 * 查询数据
	 */
	@Test
	public void query(){
	//查询id
		print("find id=2.0 "+things.find(new BasicDBObject("_id", 2.0)).toArray());
		print("find  id=54c3483de56e31f66c1c3826:"+things.find(new BasicDBObject("_id", new ObjectId("54c3483de56e31f66c1c3826"))).toArray());
		//查询1.0<id<=3的
	   Map<String,Integer> map=new HashMap<String,Integer>();
	   map.put("$gt",1);
	   map.put("$lte",3);
		print("find 1.0<id<=3"+things.find(new BasicDBObject("_id", new BasicDBObject(map))).toArray());
	   //查询id!=3
		print("find id!=1"+things.find(new BasicDBObject("_id",new BasicDBObject("$ne", "3"))).toArray());
		//查询id属于1 2
		BasicDBObject query=new BasicDBObject();
		query.put("_id", new BasicDBObject(QueryOperators.IN, new int[]{1,2}));
	   print("find id in 1.0/2.0"+things.find(query).toArray());
		//查询id不属于1 2
		BasicDBObject query1=new BasicDBObject();
		query1.put("_id", new BasicDBObject(QueryOperators.NIN, new int[]{1,2}));
	    print("find id nin 1.0/2.0"+things.find(query1).toArray());
	    //查询没有name字段的
	    print("find name exists排序"+things.find(new BasicDBObject("name", new BasicDBObject(QueryOperators.EXISTS, true))).toArray());
	    //只查询name属性
	    print("只查询name属性"+things.find(new BasicDBObject(null, new BasicDBObject("name", true))));
	    //查询修改,删除
	    print("findAndRemove查询id=54c857db28e00e31ec7c57aa的数据,并且删除:"+things.findAndRemove(new BasicDBObject("_id",new ObjectId("54c857db28e00e31ec7c57aa"))));
	    //查询_id=54c857db28e00e31ec7c57ab,并且修改name的值为"aaa"
	    print("findAndModify:"+things.findAndModify(new BasicDBObject("_id", new ObjectId("54c857db28e00e31ec7c57ab")), new BasicDBObject("name", "123")));
	}
	/**
	 * 其他操作
	 */
	@Test
	public void testOthers(){
		DBObject thing=new BasicDBObject();
		thing.put("name", "hoojo");
		thing.put("age",20);
		//JSON对象转换
		print("serialize"+JSON.serialize(thing));
		//反序列化
		print("parse:"+JSON.parse("{\"name\":\"hoojo\",\"age\":20}"));
       //判断集合是否存在
		print("判断temp Collectionshi是否存在"+db.collectionExists("things"));
		//如果不存在就创建
		if(!db.collectionExists("things")){
			DBObject th=new BasicDBObject();
			th.put("size", 20);
			th.put("copped",20);
			th.put("max",20);
			print(db.createCollection("th", th));
		}
		//设置db为只读
		db.setReadOnly(true);
		//只读不能写入数据
	}
}


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值