MongoDb查询
//数据转换类型mongodb过滤数据并聚合
db.IotMeterGasUsedRecord_2020.aggregate([{ // 获取字段 $project: { _id: 0, // 类型转换 RecordUsedValue: { $toDouble: { $substrBytes: ["$RecordUsedValue", 0, 4] } }, RecordUserId: 1 } }, { $group: { _id: "$RecordUserId", RecordUsedValue: { $sum: ("$RecordUsedValue") } } }]);
//过滤重复数据
db.IotMeterUnReportRecord_2021.aggregate([ { $group:{_id:{RecordUserId:'$RecordUserId',RecordYear:'$RecordYear',RecordMonth:'$RecordMonth',RecordDay:'$RecordDay'},count:{$sum:1},dups:{$addToSet:'$_id'}} }, { $match:{count:{$gt:1}} } ]) .forEach(function(it){ // 所动首条 it.dups.shift(); db.IotMeterUnReportRecord_2021.remove({_id: {$in: it.dups}}); }); db.IotMeterUnReportRecord_2020.aggregate([ { $group:{_id:{RecordUserId:'$RecordUserId',RecordYear:'$RecordYear',RecordMonth:'$RecordMonth',RecordDay:'$RecordDay'},count:{$sum:1},dups:{$addToSet:'$_id'}} }, { $match:{count:{$gt:1}} } ]).forEach(function(it){ it.dups.shift(); db.IotMeterUnReportRecord_2020.remove({_id: {$in: it.dups}}); });
取分组条数
db.getCollection('IotMeterUnReportRecord_2021').aggregate([{ $group: { _id: "$RecordUserId", id: { $first: "$_id" } } }, { $project: { _id: 0, id: "$id" } }, { $sort: { RecordAddDate: - 1 } }, { $skip: 10 }, { $limit: 10 }]) db.getCollection('IotMeterUnReportRecord_2021').aggregate([{ $group: { _id: "$RecordUserId", id: { $first: "$_id" }, count: { $sum: 1 } } }, { $project: { _id: 0, id: "$id" } }, { $sort: { RecordAddDate: - 1 } }, { $group: { _id: "$id", count: { $sum: 1 } } }, { $group: { _id: "$count", count: { $sum: 1 } } }])