抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

记录MongoDB相关命令

MongoDB 排序

升序

  • 查询one集合中的数据并根据age字段进行升序排序

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // 查询one集合中的数据并根据age字段进行升序排序
    Martin> db.one.find().sort({"age": 1})
    [
    { _id: ObjectId('666862463ebdc4e4a4cdcdf6'), name: 'li' },
    { _id: ObjectId('666862763ebdc4e4a4cdcdf7'), name: 'zeng', age: 16 },
    { _id: ObjectId('6668627f3ebdc4e4a4cdcdf8'), name: 'wang', age: 20 },
    { _id: ObjectId('6668628a3ebdc4e4a4cdcdf9'), name: 'zhang', age: 24 },
    { _id: ObjectId('666862943ebdc4e4a4cdcdfa'), name: 'li', age: 28 }
    ]
  • 查询one集合中age大于20并根据age进行升序排序

    1
    2
    3
    4
    5
    6
    // 查询one集合中age大于20并根据age进行升序排序
    Martin> db.one.find({age: {$gt: 20}}).sort({"age": 1})
    [
    { _id: ObjectId('6668628a3ebdc4e4a4cdcdf9'), name: 'zhang', age: 24 },
    { _id: ObjectId('666862943ebdc4e4a4cdcdfa'), name: 'li', age: 28 }
    ]

降序

  • 查询one集合中的数据并根据age字段进行降序排序

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // 查询one集合中的数据并根据age字段进行降序排序
    Martin> db.one.find().sort({"age": -1})
    [
    { _id: ObjectId('666862943ebdc4e4a4cdcdfa'), name: 'li', age: 28 },
    { _id: ObjectId('6668628a3ebdc4e4a4cdcdf9'), name: 'zhang', age: 24 },
    { _id: ObjectId('6668627f3ebdc4e4a4cdcdf8'), name: 'wang', age: 20 },
    { _id: ObjectId('666862763ebdc4e4a4cdcdf7'), name: 'zeng', age: 16 },
    { _id: ObjectId('666862463ebdc4e4a4cdcdf6'), name: 'li' }
    ]
  • 查询one集合中age大于20并根据age进行降序排序

    1
    2
    3
    4
    5
    6
    // 查询one集合中age大于20并根据age进行降序排序
    Martin> db.one.find({age: {$gt: 20}}).sort({"age": -1})
    [
    { _id: ObjectId('666862943ebdc4e4a4cdcdfa'), name: 'li', age: 28 },
    { _id: ObjectId('6668628a3ebdc4e4a4cdcdf9'), name: 'zhang', age: 24 }
    ]

求和

求集合的文档总数

  • 查询one集合中的文档总数

    1
    2
    3
    // 查询one集合中的文档总数
    Martin> db.one.countDocuments()
    5
  • 查询one集合中age大于20的文档数量

    1
    2
    3
    // 查询one集合中age大于20的文档数量
    Martin> db.one.find({age: {$gt: 20}}).count()
    2

某个字段求和

导入测试数据

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
32
33
34
35
36
37
38
39
// 导入测试数据
Martin> db.three.insertMany([{name: "li", class: 1, score: 89}, {name: "zhang", class: 1, score: 92}, {name: "li", class: 2, score: 94}, {name: "liu", class: 2, score: 88}])
{
acknowledged: true,
insertedIds: {
'0': ObjectId('666866c33ebdc4e4a4cdcdfb'),
'1': ObjectId('666866c33ebdc4e4a4cdcdfc'),
'2': ObjectId('666866c33ebdc4e4a4cdcdfd'),
'3': ObjectId('666866c33ebdc4e4a4cdcdfe')
}
}
// 查询three集合中所有数据
Martin> db.three.find()
[
{
_id: ObjectId('666866c33ebdc4e4a4cdcdfb'),
name: 'li',
class: 1,
score: 89
},
{
_id: ObjectId('666866c33ebdc4e4a4cdcdfc'),
name: 'zhang',
class: 1,
score: 92
},
{
_id: ObjectId('666866c33ebdc4e4a4cdcdfd'),
name: 'li',
class: 2,
score: 94
},
{
_id: ObjectId('666866c33ebdc4e4a4cdcdfe'),
name: 'liu',
class: 2,
score: 88
}
]
  • 对不同class进行score求和
    1
    2
    3
    4
    5
    Martin> db.three.aggregate([{'$group': {'_id': '$class', 'sum_score': {'$sum': '$score'}}}])
    [
    { _id: 1, sum_score: 181 },
    { _id: 2, sum_score: 182 }
    ]

平均

aggregate()用法解释

示例: db.collection_name.aggregate([{'$group': {'_id': '$group_filed', 'avg_xxx': {'$avg': '$avg_filed'}}}])

  • $group: 分组;
  • _id: 分组后的标识;
  • $group_filed: 分组的字段;
  • avg_xxx: 聚合之后的字段名;
  • $avg: 表示求平均值, $sum表示求和, $max: 表示求最大值, $min: 表示求最小值;
  • $avg_filed: 要聚合的字段;
  • 求平均值

    1
    2
    3
    4
    5
    6
    // 根据班级求各班的平均值
    Martin> db.three.aggregate([{'$group': {'_id': '$class', avg_score: {'$avg': '$score'}}}])
    [
    { _id: 2, avg_score: 91 },
    { _id: 1, avg_score: 90.5 }
    ]
  • 求分组最大值

    1
    2
    3
    4
    5
    6
    // 求分组最大值
    Martin> db.three.aggregate([{'$group': {_id: '$class', 'max_score': {'$max': '$score'}}}])
    [
    { _id: 1, max_score: 92 },
    { _id: 2, max_score: 94 }
    ]
  • 求分组最小值

    1
    2
    3
    4
    5
    6
    // 求分组最小值
    Martin> db.three.aggregate([{'$group': {_id: '$class', 'min_score': {'$min': '$score'}}}])
    [
    { _id: 1, min_score: 89 },
    { _id: 2, min_score: 88 }
    ]

索引

提高检索的速度

单键索引

  • 添加测试数据

    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
    // 使用for循环添加数据
    Martin> for (var i=1; i<=10000; i++) db.four.insert({num: i, name: 'a'})
    DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
    {
    acknowledged: true,
    insertedIds: { '0': ObjectId('666d8638f6e0bc9a3ecdf505') }
    }
    Martin> db.four.find()
    [
    { _id: ObjectId('666d862af6e0bc9a3ecdcdf6'), num: 1, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdcdf7'), num: 2, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdcdf8'), num: 3, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdcdf9'), num: 4, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdcdfa'), num: 5, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdcdfb'), num: 6, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdcdfc'), num: 7, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdcdfd'), num: 8, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdcdfe'), num: 9, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdcdff'), num: 10, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdce00'), num: 11, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdce01'), num: 12, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdce02'), num: 13, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdce03'), num: 14, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdce04'), num: 15, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdce05'), num: 16, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdce06'), num: 17, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdce07'), num: 18, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdce08'), num: 19, name: 'a' },
    { _id: ObjectId('666d862af6e0bc9a3ecdce09'), num: 20, name: 'a' }
    ]
    Type "it" for more
  • 创建索引

    1
    2
    3
    // 创建索引, 1为升序索引, -1为降序索引
    Martin> db.four.createIndex({"num": 1})
    num_1
  • 查询索引

    1
    2
    3
    4
    5
    6
    // 查询索引
    Martin> db.four.getIndexes()
    [
    { v: 2, key: { _id: 1 }, name: '_id_' },
    { v: 2, key: { num: 1 }, name: 'num_1' }
    ]
  • 删除索引

    1
    2
    3
    4
    5
    // 删除索引
    Martin> db.four.dropIndex("num_1")
    { nIndexesWas: 2, ok: 1 }
    Martin> db.four.getIndexes()
    [ { v: 2, key: { _id: 1 }, name: '_id_' } ]

组合索引

1
2
3
4
5
6
7
8
// 创建组合索引
Martin> db.four.createIndex({"num": 1, "name": 1})
num_1_name_1
Martin> db.four.getIndexes()
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { num: 1, name: 1 }, name: 'num_1_name_1' }
]

多值索引(组合索引)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 写入测试数据
Martin> db.five.insert({name: "martin", tag: ["a", "b", "c"]})
{
acknowledged: true,
insertedIds: { '0': ObjectId('666d8a8ef6e0bc9a3ecdf506') }
}
// 创建多值索引
Martin> db.five.createIndex({tag: 1})
tag_1
// 查询数据
Martin> db.five.find({tag: "b"})
[
{
_id: ObjectId('666d8a8ef6e0bc9a3ecdf506'),
name: 'martin',
tag: [ 'a', 'b', 'c' ]
}
]

全文索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 创建全文索引(name字段), 一个集合最多创建一个全文索引
Martin> db.five.createIndex({"name": "text"})
name_text
// 获取索引
Martin> db.five.getIndexes()
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { tag: 1 }, name: 'tag_1' },
{
v: 2,
key: { _fts: 'text', _ftsx: 1 },
name: 'name_text',
weights: { name: 1 },
default_language: 'english',
language_override: 'language',
textIndexVersion: 3
}
]

哈希索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 创建哈希索引, 哈希索引不支持范围索引并且不支持多键哈希
Martin> db.five.createIndex({name: "hashed"})
name_hashed
Martin> db.five.getIndexes()
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { tag: 1 }, name: 'tag_1' },
{
v: 2,
key: { _fts: 'text', _ftsx: 1 },
name: 'name_text',
weights: { name: 1 },
default_language: 'english',
language_override: 'language',
textIndexVersion: 3
},
{ v: 2, key: { name: 'hashed' }, name: 'name_hashed' }
]

地理位置索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 添加测试数据
Martin> db.six.insertMany([{loc: [9, 9]}, {loc: [11, 11]}, {loc: [100, 100]}])
{
acknowledged: true,
insertedIds: {
'0': ObjectId('666d8d75f6e0bc9a3ecdf507'),
'1': ObjectId('666d8d75f6e0bc9a3ecdf508'),
'2': ObjectId('666d8d75f6e0bc9a3ecdf509')
}
}
// 创建地理位置索引
Martin> db.six.createIndex({loc: "2d"})
loc_2d
// 查询在[10, 10]~[12, 12]之间的数据
Martin> db.six.find({loc: {$geoWithin: {$box: [[10, 10], [12, 12]]}}})
[ { _id: ObjectId('666d8d75f6e0bc9a3ecdf508'), loc: [ 11, 11 ] } ]

MongoDB查询计划

MongoDB慢查询

  • 查看是否开启慢查询
    1
    2
    3
    4
    Martin> db.getProfilingStatus()
    { was: 0, slowms: 100, sampleRate: 1, ok: 1 }
    // was: 表示级别 0 - 不开启 1 - 记录慢查询(默认>100ms) 2 - 记录所有命令
    // slowms: 表示慢查询时间设定值

Go操作MongoDB

  • 创建连接

    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
    32
    33
    34
    35
    // MongoDB连接配置
    client, err := mongo.NewClient(options.Client().ApplyURI("xxx"))

    // 错误判断
    if err != nil {
    fmt.Errorf("client establish failed, err: %v", err)
    }

    // 超时控制
    ctx, cancel := context.WithTimeout(context.Background(), 10 * time.Second)
    defer cancel()

    // 创建连接
    if err = client.Connect(ctx); err == nil {
    fmt.Println("connect to db success")
    }

    // 连接database
    db := client.Database("Martin")

    // 获取集合名
    collectionNames, err := db.ListCollectionNames(ctx, bson.M{})
    if err != nil {
    fmt.Errorf("err: %v", err)
    }

    // 输出集合名
    fmt.Println("collectionNames: ", collectionNames)

    // 断开连接
    defer func() {
    if err = client.Disconnect(ctx); err != nil {
    panic(err)
    }
    }
  • 创建文档

    1
    2
    // 写入当行文档

评论