MongoDB 常用java API

以下是整理一些常用的mongoDB java客户端api:

新增,更新,查找(过滤、分页)、聚合、mapReduce、索引等

package com.note;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.junit.Before;
import org.junit.Test;

import com.mongodb.AggregationOptions;
import com.mongodb.BasicDBObject;
import com.mongodb.Cursor;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MapReduceOutput;
import com.mongodb.MongoClient;

public class MongoDBTest {
	/**
	 * ip
	 */
	private static final String host= "xxxx";
	/**
	 * 端口
	 */
	private static final int port= 27017;
	/**
	 * 客户端
	 */
	private MongoClient mongoClient;
	
	/**
	 * 连接
	 * @throws Exception
	 */
	@Before
	public void connet() throws Exception {
		mongoClient = new MongoClient(host, port);
	}
	
	/**
	 * 获取db
	 * @param db
	 * @return
	 * @throws Exception
	 */
	private DB getDB(String db) throws Exception {
		return mongoClient.getDB(db);
	}
	
	/**
	 * 获取集合
	 * @param db
	 * @param collectionName
	 * @return
	 */
	private DBCollection getCollection(DB db, String collectionName) {
		return db.getCollection(collectionName);
	}
	
	/**
	 * 创建索引
	 * @throws Exception
	 */
	@Test
	public void ensureIndex() throws Exception {
		DB db = getDB("test");
		DBCollection collection = getCollection(db, "test");
		collection.createIndex(new BasicDBObject("name", 1).append("age", 1));
		//查看索引是否生效
		DBObject explain = collection.find(new BasicDBObject("name", "test")).explain();
		System.err.println(explain);
	}
	
	/**
	 * 查找  分页、排序、过滤
	 * @throws Exception
	 */
	@Test
	public void filterFind() throws Exception {
		DB db = getDB("test");
		DBCollection collection = getCollection(db, "test");
		DBCursor dbCursor = collection.find(new BasicDBObject("age", new BasicDBObject("$gt", 15).append("$lt", 18))).sort(new BasicDBObject("name", 1)).skip(1).limit(5);
		while (dbCursor.hasNext()) {
			DBObject next = dbCursor.next();
			System.err.println(next.toMap());
		}
	}
	
	/**
	 * 新增  集合、单条
	 * @throws Exception
	 */
	@Test
	public void insert() throws Exception {
		DB db = getDB("test");
		DBCollection collection = getCollection(db, "test");
		DBObject dbObject = new BasicDBObject();
		dbObject.put("name", "test");
		dbObject.put("age", 15);
		DBObject dbObject2 = new BasicDBObject();
		dbObject2.put("name", "test3");
		dbObject2.put("age", 17);
		DBObject dbObject3 = new BasicDBObject();
		dbObject3.put("name", "test4");
		dbObject3.put("age", 18);
		
		List<DBObject> list = new ArrayList<>();
		list.add(dbObject);
		list.add(dbObject2);
		list.add(dbObject3);
		collection.insert(list);
	}
	
	/**
	 * 更新单条
	 * @throws Exception
	 */
	@Test
	public void update() throws Exception {
		DB db = getDB("test");
		DBCollection collection = getCollection(db, "test");
		DBObject findOne = collection.findOne(new BasicDBObject("name", "test"));
		findOne.put("age", 15);
		collection.update(collection.findOne(new BasicDBObject("name", "test")), new BasicDBObject("$set", findOne), true, true);
	}
	
	/**
	 * 查找并更新
	 * 同理:push addToSet(去重检验) pushAll pull(值) pop(序列) rename等
	 * @throws Exception
	 */
	@Test
	public void findAndModify() throws Exception {
		DB db = getDB("test");
		DBCollection collection = getCollection(db, "test");
		collection.findAndModify(collection.findOne(new BasicDBObject("name", "test")), 
				new BasicDBObject("$push", new BasicDBObject("addr", "address")));
	}
	
	/**
	 * 统计汇合
	 * @throws Exception
	 */
	@Test
	public void mapReduce() throws Exception {
		DB db = getDB("test");
		DBCollection collection = getCollection(db, "test");
		MapReduceOutput mapReduce = collection.mapReduce("function() { emit(this.name, this.age)}", 
				"function(key, values) { return Array.sum(values)}",
				"tmp_mo_spcode_consignid_region_serviceid_201208_1",
				new BasicDBObject("age", new BasicDBObject("$gte", 15).append("$lte", 18)));
		Iterator<DBObject> iterator = mapReduce.results().iterator();
		while (iterator.hasNext()) {
			DBObject dbObject = (DBObject) iterator.next();
			System.err.println(dbObject);
		}
	}
	
	/**
	 * 分组 同理 count、min、sum、avg等
	 * @throws Exception
	 */
	@Test
	public void aggregate() throws Exception {
		DB db = getDB("test");
		DBCollection collection = getCollection(db, "test");
		List<DBObject> list = new ArrayList<>();
		DBObject dbObject = new BasicDBObject("$group", new BasicDBObject("_id", "$name").append("max", new BasicDBObject("$max", "$age")));
		list.add(dbObject);
		Cursor cursor = collection.aggregate(list, AggregationOptions.builder().allowDiskUse(true).build());
		while (cursor.hasNext()) {
			DBObject dbObject2 = (DBObject) cursor.next();
			System.err.println(dbObject2);
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值