NutzCN Logo
分享 分享:MongoDB 分组求平均值 (nutzboot)
发布于 2059天前 作者 大鲨鱼 2390 次浏览 复制 上一个帖子 下一个帖子
标签:

查询语句

db.dev_data_log.aggregate([{"$match":{"mid":"11000001","mfrsNo":"0","uploadAt":{"$gte":1514736000,"$lte":1557213280}}}, {"$group":{"_id":"$uploadDate","avgBatteryVoltage":{"$avg":"$batteryVoltage"}}}, {"$sort":{"uploadAt":-1}}, {"$limit":10}])

````
java代码(注意条件顺序)
 //日平均电池电压统计
public List<NutMap> dayAvgDatteryVoltage(String mid, String mfrsNo, long startTs, long endTs, int pageSize) {
    List<DBObject> pipeline = new ArrayList<>();
    DBObject group = new BasicDBObject();
    DBObject match = new BasicDBObject();
    DBObject sort = new BasicDBObject();
    DBObject limit = new BasicDBObject();
    NutMap groupMap = NutMap.NEW()
            .addv("_id", "$uploadDate")
            .addv("avgBatteryVoltage", NutMap.NEW()
                    .addv("$avg", "$batteryVoltage"));
    group.putAll(NutMap.NEW().addv("$group", groupMap));
    NutMap matchMap = NutMap.NEW();
    matchMap.addv("mid", mid);
    matchMap.addv("mfrsNo", mfrsNo);
    matchMap.addv("uploadAt", NutMap.NEW().addv("$gte", startTs).addv("$lte", endTs));
    match.putAll(NutMap.NEW().addv("$match", matchMap));
    sort.putAll(NutMap.NEW().addv("$sort", NutMap.NEW().addv("uploadAt", -1)));
    limit.putAll(NutMap.NEW().addv("$limit", pageSize));
    pipeline.add(match);
    pipeline.add(group);
    pipeline.add(sort);
    pipeline.add(limit);
    Cursor cursor = zMoCoDevLog.aggregate(pipeline, AggregationOptions.builder().build());
    List<NutMap> list = new ArrayList<>();
    while (cursor.hasNext()) {
        list.add(ZMoDoc.WRAP(cursor.next()).toNutMap());
    }
    return list;
}

        this.zMoDB = ioc.get(ZMoDB.class, "zmodb");
        this.zMoCoDevLog = zMoDB.cc(DevConstant.MONOGO_KEY_DEV_LOG, false);

```

1 回复

纠正下,排序条件
{"$sort":{"uploadAt":-1}}
应改为
{"$sort":{"_id":-1}}

因为结果集里没有uploadAt ~~~~

添加回复
请先登陆
回到顶部