• MONGO常用操作指令


    配置:

    1. // 结果50行为1批展示
    2. DBQuery.shellBatchSize = 50

    创建:

    1. // 创建表
    2. db.createCollection('table_name')
    3. // 创建索引(unique可选 是否唯一索引)
    4. db.getCollection("table_name").createIndex({column1: 1, column2: 1},{unique: true});

    查询:

    基础查询

    find语法
    1. db.collection.find(query, projection)
    2. query 为可选项,设置查询操作符指定查询条件;
    3. projection 也为可选项,表示使用投影操作符指定返回的字段,如果忽略此选项则返回所有字段。
    示例
    1. // 单条件查询
    2. db.getCollection("table_name").find({"_id" : ObjectId("626003cb3eecaa000aac4a22")}).limit(1000).skip(0).pretty()
    3. // 多条件查询
    4. db.getCollection("table_name").find({"_id" : ObjectId("626003cb3eecaa000aac4a22"), "column" : "value"}).limit(1000).skip(0).pretty()
    5. // 指定返回查询
    6. db.getCollection("table_name").find({"column" : "value"}, { _id: 1, column: 1}).limit(1000).skip(0).pretty()
    7. // 条件操作符查询
    8. // 常用操作符: $gt,$lt,$gte,$lte,$ne,$in,$regex,$or,$size
    9. db.getCollection("table_name").find({_id: {$in: [ObjectId("61adde77c1b7d15c5b2ca823"), ObjectId("61add448c1b7d15c5b2ca7f5")]}})
    10. // 查询结果排序(1 是升序,-1 是降序)
    11. db.getCollection("table_name").find({}, {create_time: 1}).sort({"create_time":1}).limit(1000).skip(0).pretty()

    聚合查询

    aggregate语法
    db.aggregate( [ <pipeline> ], { <options> } )
    管道操作符
    操作符描述
    $match过滤数据,只输出符合结果的文档(也可以对分组的数组做过滤)
    $project修改输入文档的结构(例如重命名,增加、删除字段,创建结算结果等)
    $group将collection中的document分组,可用于统计结果
    $unwind将数组类型的字段进行拆分([],null,以及无指定字段 的数据会丢失,若不想丢失参考下方示例)
    $sort将结果进行排序后输出
    $limit限制管道输出的结果个数
    $skip跳过制定数量的结果,并且返回剩下的结果
    $lookup多表关联查询
    1. // 会丢失[],null,以及无指定字段 的数据
    2. db.getCollection('table_name').aggregate([
    3. {
    4. $unwind: '$list'
    5. }
    6. ])
    7. // 不会丢失[],null,以及无指定字段 的数据
    8. db.getCollection('table_name').aggregate([
    9. {
    10. $unwind: {
    11. path: '$list', // path是指定字段
    12. preserveNullAndEmptyArrays: true //该属性为true即保留
    13. }
    14. }
    15. ])
    表达式操作符
    操作符描述
    $add求和
    $avg求平均值
    $concat字符串连接
    $divide求商
    $first根据文档的排序获取第一个文档数据
    $last根据文档的排序获取最后一个文档数据
    $max求最大值
    $min求最小值
    $mod求模
    $multiply求乘积
    $push将结果文档中插入值到一个数组中
    $skip跳过一些条数
    $substr字符串截取(只能匹配ASCII的数据)
    $substrCP中文字符串截取
    $subtract求差
    $sum计算总和,{$sum: 1}表示返回总和×1的值(即总和的数量),使用{$sum: '$制定字段'}也能直接获取制定字段的值的总和
    $toLower转小写
    $toUpper转大写
     示例
    1. // group
    2. db.getCollection("table_name").aggregate([{"$group": {_id:"$create_name"}}])
    3. // where + group
    4. db.getCollection("table_name").aggregate([{"$match": {create_name: "zhangsan"}}, {"$group": {_id:"$create_name"}}])
    5. // where + group + having
    6. db.getCollection("table_name").aggregate([{"$match": {create_name: "zhangsan"}}, {"$group": {_id:"$create_name", count:{$sum:1}}}, {"$match": {count:{$gt:1}}}])
    7. // 多个字段group
    8. db.getCollection("table_name").aggregate([{"$match": {create_time:{$gte:ISODate("2023-09-14T16:00:00.000Z")}}}, {"$group": {_id:{create_name: "$create_name", create_time: "$create_time"}, count:{$sum:1}}}])
    9. // sum字段
    10. db.getCollection("table_name").aggregate([{"$match": {create_time:{$gte:ISODate("2023-09-14T16:00:00.000Z")}}}, {"$group": {_id:{create_name: "$create_name", create_time: "$create_time"}, count:{$sum:"$price"}}}])
    11. // Date字段拆分
    12. db.getCollection("table_name").aggregate([{"$match": {create_time:{$gte:ISODate("2023-08-10T16:00:00.000Z")}}}, {"$group": {_id: {
    13. create_time: {
    14. month: { $month: "$create_time" },
    15. day: { $dayOfMonth: "$create_time" },
    16. year: { $year: "$create_time"}
    17. }
    18. }, count:{$sum: 1}}}])
    19. // push
    20. db.getCollection("table_name").aggregate([
    21. {
    22. $group: {
    23. _id: '$price',
    24. title: { $push: '$title' }
    25. }
    26. }
    27. ])
    28. // unwind + project + toLower + toUpper + concat + substr + substrCP + 加减乘除模
    29. db.getCollection("table_name").aggregate([
    30. { $unwind: '$数组列名' },
    31. {
    32. $project: {
    33. _id: 0,
    34. Title: '$title',
    35. tags: '$tags',
    36. New_Title: { $toLower: '$title'},
    37. New_Tags: { $toUpper: '$tags'},
    38. Title_Tags: { $concat: ['$title','-','$tags']},
    39. Title_Prefix: { $substr: ['$title',0,3]},
    40. Title_Prefix_CN: { $substrCP: ['$title',0,6]},
    41. Add_Price: { $add: ['$price',1]},
    42. Sub_Price: { $subtract: ['$price',1]},
    43. Mul_Price: { $multiply: ['$price',2]},
    44. Div_Price: { $divide: ['$price',2]},
    45. Mod_Price: { $mod: ['$price',2]}
    46. }
    47. }
    48. ])
    49. // lookup
    50. db.getCollection("source_table_name").aggregate([
    51. {
    52. $lookup:
    53. {
    54. from: "dest_table_name",
    55. localField: "source_table_name key",
    56. foreignField: "dest_table_name key",
    57. as: "new column name"
    58. }
    59. }
    60. ])
    options
    操作类型描述
    explain布尔值

    可选的。指定返回有关管道处理的信息。有关示例,请参阅 有关聚合管道操作的返回信息

    多文档交易中不可用。

    allowDiskUse布尔值

    可选的。允许写入临时文件。设置为时 true,大多数聚合操作可以将数据写入_tmp目录中的 dbPath子目录,但以下情况除外:

    • $graphLookup 阶段
    • $addToSet$group阶段中使用的累加器表达式 (从4.2.3、4.0.14、3.6.17版开始)
    • $push$group阶段中使用的累加器表达式 (从4.2.3、4.0.14、3.6.17版开始)

    MongoDB 4.2开始,事件探查器日志消息诊断日志消息包括一个usedDisk 指示符,指示是否有任何聚合阶段由于内存限制而将数据写入临时文件。

    cursor文献可选的。指定游标的初始批处理大小。该cursor 字段的值是带有该字段的文档batchSize。有关语法和示例,请参见 指定初始批处理大小
    maxTimeMS非负整数

    可选的。指定用于游标的处理操作的时间限制(以毫秒为单位)。如果未为maxTimeMS指定值,则操作不会超时。值0明确指定默认的无限制行为。

    MongoDB使用与相同的机制终止超出其分配的时间限制的操作db.killOp()。MongoDB仅在其指定的中断点之一处终止操作。

    bypassDocumentValidation布尔值

    可选的。仅当您指定$out$merge聚合阶段时适用。

    允许db.collection.aggregate在操作过程中绕过文档验证。这使您可以插入不符合验证要求的文档。

    3.2版中的新功能。

    readConcern文献

    可选的。指定读取关注

    从MongoDB 3.6开始,readConcern选项具有以下语法: readConcern: { level:  }

    可能的阅读关注级别为:

    有关阅读关注级别的更多信息,请参阅 阅读关注级别

    从MongoDB 4.2开始,此$out阶段不能与“关注”一起使用"linearizable"。也就是说,如果您为指定了"linearizable"读取关注 db.collection.aggregate(),则不能将$out阶段包括 在管道中。

    $merge阶段不能与已关注的内容一起使用"linearizable"。也就是说,如果您为指定了 "linearizable"读取关注 db.collection.aggregate(),则不能将$merge阶段包括 在管道中。

    collation文献

    可选的。

    指定 用于操作的排序规则

    归类允许用户为字符串比较指定特定于语言的规则,例如字母大写和重音符号的规则。

    排序规则选项具有以下语法:

    collation: {
       locale: ,
       caseLevel: ,
       caseFirst: ,
       strength: ,
       numericOrdering: ,
       alternate: ,
       maxVariable: ,
       backwards: 
    }
    

    指定排序规则时,该locale字段为必填字段;所有其他排序规则字段都是可选的。有关字段的说明,请参见整理文档

    如果未指定排序规则,但是集合具有默认排序规则(请参阅参考资料db.createCollection()),则该操作将使用为集合指定的排序规则。

    如果没有为集合或操作指定排序规则,则MongoDB使用先前版本中使用的简单二进制比较进行字符串比较。

    您不能为一个操作指定多个排序规则。例如,您不能为每个字段指定不同的排序规则,或者如果对排序执行查找,则不能对查找使用一种排序规则,而对排序使用另一种排序规则。

    3.4版的新功能。

    hint字符串或文件

    可选的。用于聚合的索引。索引位于运行聚合的初始集合/视图上。

    通过索引名称或索引规范文档指定索引。

    注意

    hint不适$lookup和 $graphLookup阶段。

    3.6版的新功能。

    comment

    可选的。用户可以指定任意字符串,以帮助通过数据库概要分析器,currentOp和日志来跟踪操作。

    3.6版的新功能。

    writeConcern文献

    可选的。表示 与or 阶段一起使用的写关注点的文档。$out$merge

    忽略对$outor $merge阶段使用默认的写关注。

    1. db.getCollection('table_name').aggregate([{$group: {_id: "$ds",count: { $sum: 1 }}}],{explain: "executionStats"} )
    2. db.getCollection('table_name').explain("executionStats").aggregate([{$group: {_id: "$ds",count: { $sum: 1 }}}])

    修改:

    更新语法

    1. // 已不推荐使用
    2. db.collection.update(filter, update, options)
    3. // 是对update的封装,不支持{multi:true}属性,加了也没用
    4. db.collection.updateOne(filterupdate,options) // Added in MongoDB 4.2
    5. // 是对update的封装,自动加入了 {multi:true}属性,设为false也不行
    6. db.collection.updateMany(filterupdate,options) // Added in MongoDB 4.2

    更新方法模板

    1. db.collection.update(
    2.    <filter>,
    3.    <update>,
    4.    {
    5.      upsert: <boolean>, // 默认false
    6.      multi: <boolean>, // 默认false
    7.      writeConcern: <document>,
    8.      collation: <document>,
    9.      arrayFilters: [ <filterdocument1>, ... ],
    10.      hint:  <document|string>, // Added in MongoDB 4.2
    11.      let: <document> // Added in MongoDB 5.0
    12.    }
    13. )
    14. writeConcern:可选,MongoDB写入安全机制,用于控制写入安全的级别。它指定了在写操作完成之前,MongoDB需要接收到的确认数。writeConcern级别越高,写操作的确认就越安全,但也会影响写的性能。writeConcern有三种级别,分别是:
    15. - 1:表示写操作需要写入主节点的内存中,但不需要确认写操作是否成功。这是默认级别。
    16. - majority:表示写操作需要写入大多数节点的内存中,并且需要确认写操作是否成功。
    17. - <number>:表示写操作需要写入指定数量的节点的内存中,并且需要确认写操作是否成功。
    18. 如果有需求可以查看文档:https://www.mongodb.com/docs/v5.0/reference/write-concern/

    字段更新操作符:

    操作符语法含义
    $set{ $set: { : , ... } }用指定的值替换字段的值。
    $inc{ $inc: { : , : , ... } }将字段按指定值递增
    $unset{ $unset: { : , ... } }删除一个特定的字段。
    $rename{$rename: { : , : , ... } }更新字段的名称
    $min{ $min: { : , ... } }仅当指定值小于现有字段值时才更新该字段。如果该字段不存在,则将字段设置为指定的值。
    $currentDate{ $currentDate: { : , ... } }将字段的值设置为当前日期,可以是date,也可以是timestamp。默认类型为Date。
    $max{ $max: { : , ... } }仅当指定值大于现有字段值时才更新该字段。如果该字段不存在,则将字段设置为指定的值。
    $mul{ $mul: { : , ... } }将字段的值乘以一个数字
    $setOnInsert在upsert过程中,在创建文档时设置字段的值。
    对修改现有文档的更新操作没有影响。

    数组字段更新操作符:

    操作符含义
    $标识数组中要更新的元素,而不显式指定元素在数组中的位置。(有时候你根本不知道元素具体位置;见案例篇)
    $[]充当占位符,为匹配查询条件的文档更新数组中的所有元素。
    $[]用来充当数组字段中与arrayFilters中指定的条件匹配的所有元素的占位符,必须以小写字母开头,且只能包含字母数字字符,为匹配查询条件的文档更新与arrayFilters条件匹配的所有元素。
    $addToSet仅在集合中不存在元素时才将元素添加到数组中。
    $push可以向已有数组末尾追加重复元素,要是不存在就创建一个数组。
    $pushAll可以向已有数组末尾追加多个重复元素,要是不存在就创建一个数组。
    $pop删除数组中的数据;1表示从comments数组的末尾删除一条数据,-1表示从comments数组的开头删除一条数据。
    $pull按条件删除数组中的某个元素
    $pullAll按条件删除数组中的全部元素

    更新操作符修饰符

    操作符含义
    $each将多个值追加到数组字段;
    $position指定插入元素的位置(后接索引位置,默认数组末尾)。配合$each使用;
    $slice限制数组元素的数量。配合$each使用;
    $sort对数组中的元素排序。配合$each使用。

    update示例:MongoDB update 彻底聊明白(案例篇) - 知乎

    执行返回:WriteResult

    执行完update命令之后我们应该明白MongoDB返回的信息,告诉我们成功与否以及更新了多少条等信息;db.collection.update () 方法返回一个WriteResult()对象,其中包含操作的状态。

    执行成功

    如果执行成功,WriteResult()对象将包含:

    • nMatched:匹配查询条件的文档数量
    • nUpserted:更新插入的文档数量
    • nModified:修改的文档数量
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

    执行失败

    如果执行失败,WriteResult对象除了成功哪些字段之外,还包含writeConcernError,比较重要的信息有错误信息(errmsg).如下显示写入复制节点超时:

    1. WriteResult({
    2.    "nMatched" : 1,
    3.    "nUpserted" : 0,
    4.    "nModified" : 1,
    5.    "writeConcernError": {
    6.      "code" : 64,
    7.      "errmsg" : "waiting for replication timed out",
    8.      "errInfo" : {
    9.        "wtimeout" : true,
    10.        "writeConcern" : {
    11.          "w" : "majority",
    12.          "wtimeout" : 100,
    13.          "provenance" : "getLastErrorDefaults"
    14.        }
    15.    }
    16. })

    1. 示例:
    2. // set更新数据
    3. db.getCollection("table_name").update({"_id" : ObjectId("628cbae13b7750c6711d09f4")}, {$set:{"column":"value"}}, false, true)
    4. // unset去除数据
    5. db.getCollection("table_name").update({"_id" : ObjectId("628cbae13b7750c6711d09f4")}, {$unset:{"column":"value"}}, {upsert:true, multi:true})
    6. // push添加数据
    7. db.getCollection("table_name").update({"_id" : ObjectId("628cbae13b7750c6711d09f4")}, {"$push":{"actions" : "appeal-rule-link"}}, {"$push":{"consumers" : {
    8. "source" : "zp_serv13_appeal_audit",
    9. "timeOut" : NumberInt("1000")
    10. }}})
    11. // pull移除数据
    12. db.getCollection("table_name").update({"_id" : ObjectId("628cbae13b7750c6711d09f4")}, {"$pull":{"actions" : ["appeal_check_dispose"]}})

    删除:

    1. // 指定query删除
    2. db.getCollection("table_name").remove({create_time:{$gte:ISODate("2023-08-29T01:55:38.000Z"),$lte:ISODate("2023-08-29T01:56:37.999Z")}})

    批量操作

    1. // String转Int
    2. db.getCollection('table_name').find({column:{$type:"string"}}).forEach(
    3. function(item){
    4. item.column=NumberInt(item.column);
    5. db.getCollection('table_name').save(item);
    6. }
    7. )
    8. // ..._...转...-...
    9. db.getCollection('table_name').find({column:{$regex:"-"}}).forEach(
    10. function(item){
    11. item.column = item.column.replace('_', '-');
    12. db.getCollection('table_name').update({"_id":item._id},{"$set":{"column":item.column}});
    13. }
    14. )
    15. // ...aaa...转...bb...
    16. db.getCollection('table_name').find({'column':{'$regex': /aaa/ }}).forEach(
    17. function(item) {
    18. var tmp = String(item.column)
    19. tmp = tmp.replace('aaa','bb')
    20. if (tmp == null){
    21. print(item.column)
    22. }
    23. item.column = tmp ;
    24. db.table_name.save(item);
    25. });
    26. db.getCollection('table_name').updateMany(
    27. {'column':{'$regex': "aaa"}},
    28. {
    29. $set: {column: {
    30. $replaceOne: { input:"$column", find:"aaa", replacement:"bb" }
    31. }}
    32. }
    33. );

    其他:

    1. // 计数
    2. db.getCollection("table_name").count()
    3. // mongo数据导入导出
    4. 1.导出 ./bin/mongoexport -h 'host' -p 'port' --username 'username' --password 'password' -d 'database_name' -c 'collection_name' --authenticationDatabase 'auth' -o dump.txt
    5. 2.压缩 tar -zcf dump.tar.gz dump.txt
    6. 3.下载 downloadfile dump.tar.gz
    7. 4.导入 ./bin/mongoimport -h 'host' -p 'port' --username 'username' --password 'password' -d 'database_name' -c 'collection_name' --authenticationDatabase 'auth' /../dump.txt

  • 相关阅读:
    react框架与vue框架的区别
    模块化打包工具-初识Webpack
    Spring和Spring Mvc整合详解
    python环境搭建
    【网页设计】基于LayUI的N站新闻门户页面
    清理Linux操作系统buff/cache缓存
    spring5:IOC操作bean管理(创建对象和set属性注入)
    从零开始学mitmproxy抓包工具
    Java poi操作Excel单元格样式
    Linux more 命令使用介绍
  • 原文地址:https://blog.csdn.net/zxx2096/article/details/125413940