MongoDb查询和分组统计示例

本文介绍了一种利用MongoDB进行数据统计的方法,并展示了如何通过特定条件筛选和分组用户数据,同时实现了根据用户ID获取其好友医生列表的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 按周统计:   
                             DBCollection userSColl = db.getCollection("paysource");

BasicDBObject key = new BasicDBObject("userId", true);

BasicDBObject cond = new BasicDBObject("userId", userId);

SimpleDateFormat sdf = new SimpleDateFormat(

"yyyy-MM-dd HH:mm:ss");

cond.put(

"createtime",

new BasicDBObject("$gte", sdf

.format(getTimesWeekmorning())).append("$lte",

sdf.format(getTimesWeeknight())));

BasicDBObject initial = new BasicDBObject("praise", 0);

String reduce = "function(obj,pre){pre.praise+=obj.money}";

BasicDBList returnList = (BasicDBList) userSColl.group(key,

cond, initial, reduce);

if (returnList.size() > 0) {

DBObject obj = (DBObject) returnList.get(0);

money = Double.parseDouble(obj.get("praise").toString());

List<FreindDoctor> docts = new ArrayList<FreindDoctor>();

List<String> mobiles = getFreindMobiles(userId);

DB db = MyMongo.getDB();

if (db != null) {

DBCollection collection = db.getCollection("user");

BasicDBList values = new BasicDBList();

for (String info : mobiles) {

values.add(info);

}

BasicDBObject cond = new BasicDBObject();

cond.put("typeId", User.DOCTOR);

cond.put("userId", new BasicDBObject("$in", values));

DBCursor cursor = collection.find(cond);

try {

while (cursor.hasNext()) {

DBObject obj = cursor.next();

User doctor = gson.fromJson(obj.toString(), User.class);

if (doctor != null) {

FreindDoctor tm = new FreindDoctor();

tm.doctorId = doctor.userId;

ContactBean cont=getFreind(userId,doctor.userId);

tm.doctorName =cont.name;

tm.healUrl=doctor.headUrl;

docts.add(tm);

}

}

} catch (Exception e) {

logger.error("getContactDoctors " + e.getMessage());

} finally {

cursor.close();

}

}

 

转载于:https://my.oschina.net/u/778683/blog/829009

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值