mongodb原生查询语句
db.getCollection(‘chillerDB’).aggregate([
{$match:{‘timestamp’:{‘$gte’:1575907200000,’$lte’:1575993600000},’regionId’:2}},
{‘$sample’:{‘size’:49}},
{$group:
{_id:
{‘time’:’$createTime’,
‘timestamp’:’$timestamp’,
‘chillerPower’:{$sum:’$listChiller.chillerPower’},
‘frozenPumPower’:{$sum:’$listFrozenPum.frozenPumPower’},
‘coolingPumpPower’:{$sum:’$listCoolingPump.coolingPumpPower’},
‘coolingTowerPower’:{$sum:’$listCoolingTower.coolingTowerPower’},
‘totalPower’:’$totalPower’,
}
}
},
{‘$sort’:{‘_id.timestamp’:1}},])
Java代码示例
String tableName = “chillerDB”;
String sql = “[{$match:{‘timestamp’:{‘$gte’:1575907200000,’$lte’:1575993600000},’regionId’:2}},{‘$sample’:{‘size’:1000}},{$group:{_id:{‘time’:’$createTime’,’timestamp’:’$timestamp’,’chillerPower’:{$sum:’$listChiller.chillerPower’},’frozenPumPower’:{$sum:’$listFrozenPum.frozenPumPower’},’coolingPumpPower’:{$sum:’$listCoolingPump.coolingPumpPower’},’coolingTowerPower’:{$sum:’$listCoolingTower.coolingTowerPower’},’totalPower’:’$totalPower’,}}},{‘$sort’:{‘_id.timestamp’:1}}]”;
List basicDBObjectList = JSONArray.parseArray(sql,BasicDBObject.class);
AggregateIterable aggregate = mongoTemplate.getDb().getCollection(tableName).aggregate(basicDBObjectList);
MongoCursor mongoCursor = aggregate.iterator();
List documentList = new ArrayList<>(1000);
while (mongoCursor.hasNext()){
Document doc = mongoCursor.next();
documentList.add(doc);
}