MongoDB在java中各种查询

import java.net.UnknownHostException;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
public class MongoDBTest {
	private static DB db = null; 
	
	static{
		Mongo mongo = null;
		try {
			mongo = new Mongo("localhost", 27017);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		db = mongo.getDB("TestDB");	//连接数据
	}
	
	/**
	 * select count(*) from list
	 */
	public Long m1() {
		DBCollection collection = db.getCollection("list");
		return collection.count();
	}
	
	/**
	 * select count(*) from list where userId = 'orange'
	 */
	public Long m2(){
		DBCollection listCollection = db.getCollection("list");
		BasicDBObject query =new BasicDBObject();
		query.put("userId", "orange");
		return listCollection.count(query);
	}
	
	
	/**
	 * select count(*) from list where userId = 'orange' and time >= '20101201' and time <= '20101211'
	 */
	public Long m3(){
		DBCollection listCollection = db.getCollection("list");
		BasicDBObject query =new BasicDBObject();
		query.put("userId","orange");
		query.put("time", new BasicDBObject("$gte", "20101201").append("$lte", "20101211"));
		return listCollection.count(query);
	}


	/**
	 * select count(distinct(userId)) from detail where time >= '20101201' and time <='20101211'
	 */
	public int m4() {  
		DBCollection collection = db.getCollection("detail");
		BasicDBObject query = new BasicDBObject(); 
		query.put("time", new BasicDBObject("$gte", "20101201").append("$lte", "20101211")); 
		return collection.distinct("userId", query).size();
	}
	
	
	/**
	 * select date_format(time, '%Y-%m-%d %H') as sj ,count(*) from detail group by sj
	 */
	public void m5() {
		DBCollection collection = db.getCollection("detail");
		String formatDate = "function(obj,doc){"
				+ "var date = new Date(doc.time);"
				+ "var dateKey = date.getFullYear()+\"-\"+(date.getMonth()+1)+\"-\"+date.getDate(); "
				+ "return {'time':datekey}" + "}";
		BasicDBObject key = new BasicDBObject();
		key.put(formatDate, true); // 要分组的列
		BasicDBObject query = new BasicDBObject(); // where条件
		String reduce = "function (obj, prev) {prev.count++}";
		BasicDBObject initial = new BasicDBObject();
		initial.append("count", 0); // 每列初始值
		BasicDBList group = (BasicDBList) collection.group(key, query, initial,	reduce);
		System.out.println(group);
	}

}
转载地址:https://blog.csdn.net/itjavaer/article/details/47953761
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值