mongoDB 常用查询与统计


概述

本篇主要是记录mongodb 使用中的常见查询与统计操作

如果在需要导入数据可以使用以下命令:

1
mongoimport -d <dbname> -c <collection> < collection.json

1. 查询

  • 所有记录

    1
    db.test.find()
  • 一条结果

    1
    db.test.findOne()
  • 限制查询结果

在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
2
查询年龄大于等于10的数据
db.test.find({age: {$get: 10}})
  • $lt 小于 (less than)
  • $lte 小于等于 (less than equals)
  • $gt 大于 (greater than)
  • $gte 大于等于 (greater than equals)
  • $ne 不等于 (not equals)

判断是否存在改字段 $exists

1
2
查询age 字段不存在的记录
db.test.find({age: {exists: true}})

判断是否存在该字段或者为空 null

1
2
查询age 字段不存在 或者值为null的记录
db.test.find({age: null})

null$exists的区别就是null 包含了字段不存在的情况

$in$nin的查询

1
2
查询年龄为10, 11 的所有记录
db.test.find({age: {$in: [10, 11]}})

这个类似sql的in与not in

$or 或操作

1
db.test.find({$or: [{name: 'test'}, {age: 10}]})

类似sql中的or

$all查询满足所有条件的记录

一般用于多分类情况 例如以下两条记录

1
2
{userName: 'test1', tag: [1,2,3,4]}
{userName: 'test2', tag: [1,2,3]}
1
2
db.test.find({tag: {$all: [1, 4]}})
会查询出第一条

2. 统计

  • count统计所有

1
db.test.find({}).count()
  • distinct() 去重统计

1
2
3
4
db.test.distinct('userName').length

条件去重统计
db.test.distinct('userName', {age: 10}).length
  • 分组统计

以下例子是根据 project 和day 分组统计

1
2
3
4
5
6
7
8
db.getCollection('report_test').aggregate([
{
$group: {
_id: {project: '$project', day: '$day'},
count: {$sum: 1}
}
}
])

添加条件的分组统计

1
2
3
4
5
6
7
8
9
10
11
12
13
db.getCollection('report_test').aggregate([
{
$match: {
day: {$gte: '2017-01-01'}
}
},
{
$group: {
_id: {project: '$project', day: '$day'},
count: {$sum: 1}
}
}
])

稍微复杂一点的统计, 添加了关于时间的处理

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
db.getCollection('report_test').aggregate([
{
$project: {
house_id: "$house_id",
day: '$day',
f_available_num: "$f_available_num",
createdAt: {$add: [ "$createdAt", 8 * 3600 * 1000]}
}
},
{
$match: {createdAt: {$gte: '2017-01-01'}}
},
{
$group: {
_id: {
createdAt: {
$dateToString: {
format: "%Y-%m-%d", date: "$createdAt"
}
},
houses: "$house_id"
},
value: {$sum: "$f_available_num"}
}
}
])

mongo中文社区文档


Author: 杜宏飞
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source 杜宏飞 !
  TOC