随笔 - 833  文章 - 0  评论 - 9  阅读 - 35万

MongoDB分组查询

1. 设置显示要查询的列
```
显示 device_id,device_name,online_status,video_diag_time
db.getCollection('vqd_result_his').find({},{device_id:1,device_name:1,online_status:1,video_diag_time:1})

不显示 device_id,其他都显示
db.getCollection('vqd_result_his').find({},{device_id:0})
```

2. 设置要排序的字段
```
device_name 升序
db.getCollection('vqd_result_his').find({}).sort({'device_name':1})

device_name 降序
db.getCollection('vqd_result_his').find({}).sort({'device_name':-1})
```

3. 分组查询
```
db.vqd_result_his.aggregate([{
'$group':{'_id':'$device_id',count:{$sum:1}}}])
```

4. 多字段分组查询
```
db.vqd_result_his.aggregate([{
'$group':{'_id':{'device_id':'deviceid,online:online_status','device_name':'$device_name'},count:{$sum:1}}}])
```

5. 条件过滤后分组查询
```
db.vqd_result_his.aggregate([{
'$match':
{
'$and':[
{'video_diag_time':{'$gte':ISODate("2020-08-01T00:00:00Z")}},
{'video_diag_time':{'$lte':ISODate("2020-08-26T00:00:00Z")}}
]
}},{
'$group':{'_id':{'device_id':'deviceid,online:online_status','device_name':'$device_name'},count:{$sum:1}}}])
```

7. 查询结果转为数组
```
db.vqd_result_his.aggregate([{
'$match':
{
'$and':[
{'video_diag_time':{'$gte':ISODate("2020-08-01T00:00:00Z")}},
{'video_diag_time':{'$lte':ISODate("2020-08-26T00:00:00Z")}}
]
}},{
'$group':{'_id':{'device_id':'deviceid,online:online_status','device_name':'$device_name'},count:{$sum:1}}}]).toArray()
```

8. 创建列索引
```
db.vqd_result_his.createIndex({"device_name": -1}),此处 -1 代表倒序,1 代表正序;
```

posted on   Simle  阅读(5726)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2017-08-25 Eclipse远程调试
2016-08-25 VMware搭建12.0搭建Mac OS10.11详细过程
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示