概述
本篇主要是记录mongodb 使用中的常见查询与统计操作
如果在需要导入数据可以使用以下命令:
1 | mongoimport -d <dbname> -c <collection> < collection.json |
1. 查询
在test集合中查询 userNmame 为’test’ age 为10 的记录
1 | db.test.find({userName: 'test1', age: 10}) |
限制输出字段的查询, 例如只显示userName字段不想输出所有字段
1 | db.test.find({userName: 'test1', age: 10}, {userName: true, _id: false}) |
在mongo中
_id字段是默认输出的,如果不想显示把_id设为false
使用limit()限制结果
1 | db.test.find({age: 10}).limit(3) |
使用条件操作符
1 | 查询年龄大于等于10的数据 |
- $lt 小于 (less than)
- $lte 小于等于 (less than equals)
- $gt 大于 (greater than)
- $gte 大于等于 (greater than equals)
- $ne 不等于 (not equals)
判断是否存在改字段 $exists
1 | 查询age 字段不存在的记录 |
判断是否存在该字段或者为空 null
1 | 查询age 字段不存在 或者值为null的记录 |
null与$exists的区别就是null包含了字段不存在的情况
$in和$nin的查询
1 | 查询年龄为10, 11 的所有记录 |
这个类似sql的in与not in
$or 或操作
1 | db.test.find({$or: [{name: 'test'}, {age: 10}]}) |
类似sql中的or
$all查询满足所有条件的记录
一般用于多分类情况 例如以下两条记录
1 | {userName: 'test1', tag: [1,2,3,4]} |
1 | db.test.find({tag: {$all: [1, 4]}}) |
2. 统计
1 | db.test.find({}).count() |
1 | db.test.distinct('userName').length |
以下例子是根据 project 和day 分组统计
1 | db.getCollection('report_test').aggregate([ |
添加条件的分组统计
1 | db.getCollection('report_test').aggregate([ |
稍微复杂一点的统计, 添加了关于时间的处理
1 | db.getCollection('report_test').aggregate([ |