• mongodb常用命令


    参考:

    https://www.jb51.net/article/48217.htm (mongodb常用操作命令大全)

    https://www.jianshu.com/p/fffb581bb1a9 (mongodb常用命令)

    https://docs.mongodb.com/manual/reference/method/js-collection/ (综合:官方文档)

    查看手册

    help #直接运行,全局目录列表
    ... db.help(); db.yourColl.help(); db.youColl.find().help();

    数据库命令

    表命令

    参考:https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/#json-schema(官方文档字段结构规划)

    创建表

    db.createCollection( "contacts", {
       validator: { $jsonSchema: {
          bsonType: "object",
          required: [ "phone" ],
          properties: {
             phone: {
                bsonType: "string",
                description: "must be a string and is required"
             },
             email: {
                bsonType : "string",
                pattern : "@mongodb.com$",
                description: "must be a string and match the regular expression pattern"
             },
             status: {
                enum: [ "Unknown", "Incomplete" ],
                description: "can only be one of the enum values"
             }
          }
       } }
    } )

    行命令

    新增

    //添加一个
    db.products.insert( { item: "card", qty: 15 } )
    db.products.insertOne( { item: "card", qty: 15 } )//传数组会失败
    //批量添加 
    db.products.insert( [{ item: "card1", qty: 15 } ,{ item: "card2", qty: 15 } ])
    db.products.insertMany( [{ item: "card1", qty: 15 } ,{ item: "card2", qty: 15 } ])//传json会失败

    删除

    //删除一条
    db.orders.deleteOne( { "_id" : ObjectId("563237a41a4d68582c2509da") } );
    //删除多条(只匹配一个就删除一条)
    db.orders.deleteMany( { "_id" : ObjectId("563237a41a4d68582c2509da") } );
    //综合方法
    db.collection.remove(
       <query>,
       {
         justOne: <boolean>,//默认false,也就是删多条
         writeConcern: <document>,
         collation: <document>,
         let: <document> // Added in MongoDB 5.0
       }
    )

    查询

    查询基本方法

    db.collection.find()
    db.collection.findAndModify({
        query: <document>,
        sort: <document>,
        remove: <boolean>,
        update: <document or aggregation pipeline>, // Changed in MongoDB 4.2
        new: <boolean>,
        fields: <document>,
        upsert: <boolean>,
        bypassDocumentValidation: <boolean>,
        writeConcern: <document>,
        collation: <document>,
        arrayFilters: [ <filterdocument1>, ... ],
        let: <document> // Added in MongoDB 5.0
    });//黑科技:支持删除,修改,是否未匹配新增,

    查询单元属性,参考:https://docs.mongodb.com/manual/reference/operator/query/ (官方查询操作列表)

    //基本比较
    $eq,$ne,$in,$nin,$gt,$lt,$gte,$lte
    //单元逻辑
    $and,$or,$not,$nor //$nor: !A或!B
    //字段
    $type,$exists//类型,存在性(null也是存在)
    //数组 
    $all: [ "ssl" , "security" ] //数组类型的字段且需包含$all中所有的元素
    $elemMatch: { <query1>, <query2>, ... } //至少包含一个

    $size:<number> //数组中的元素个数为number //黑科技 $regex #正则表达式{ <field>: /pattern/<options> } $text #基于文本索引的文本搜索,必须先创建索引 $where #举例 {$where: <string|JavaScript Code>} $expr #表达式,可以组合任意单元,过于强大 //其他...

    聚合(查询)

    mongo的聚合查询比mysql的聚合查询强大太多,也包含基本查询的功能

    参考:https://docs.mongodb.com/manual/reference/operator/aggregation(单元方法)

    https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline (全局方法)

    举例:

    db.scores.aggregate([
        {
          $match: {
            score: {
              $gt: 80
            }
          }
        },
        {
          $count: "passing_scores"
        }
      ])

    聚合全局方法

    //基本语法:
    db.collection.aggregate( [ { <stage> }, ... ] )
    
    //具体方法:
    $count #基数,可以设置返回字段名称
    $match #匹配
    $group #分组标识_id
    $set #可以设置已存在或不存在的字段
    $unset #去掉设置的字段
    $project #综合属性:可以包含$addFields和$unset的作用
    $sort #排序
    $skip #跳过
    $limit #限制数量

    聚合单元属性

    #数学方法
    $add:[ <expression1>, <expression2>]
    $subtract:[ <expression1>, <expression2>]
    $multiply:[ <expression1>, <expression2>, ... ]
    $divide:[ <expression1>, <expression2>]
    $mod[<expression1>, <expression2>]
    ...
    
    #字符串方法
    $trim,$ltrim,$rtrim: { input: <string>,  chars: <string>} 
    $substr:[ <string>, <start>, <length> ] 截取
    $split: [ <string expression>, <delimiter> ] 用分隔符分割为数组
    $concat:[ <expression1>, <expression2>, ... ] 
    $toUpper,$toLower:<expression>
    $toString:<expression>
    $replaceOne,$replaceAll: { input: <expression>, find: <expression>, replacement: <expression> } 
    ...
    
    #数组方法
    $arrayElemAt: [ <array>, <idx> ]
    $concatArrays: [ <array1>, <array2>, ... ]
    $first,$last:<expression>
    $in: [ <expression>, <array expression> ]
    $indexOfArray: [ <array expression>, <search expression>, <start>, <end> ]
    $map: { input: <expression>, as: <string>, in: <expression> } 
    $filter: { input: <array>, as: <string>, cond: <expression> } 
    $slice: [ <array>, <n> ]或者[ <array>, <position>, <n> ] 
    ...
    
    #条件表达
    $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> }或者[ <boolean-expression>, <true-case>, <false-case> ]
    $ifNull: [
          <input-expression-1>,
          ...
          <input-expression-n>,
          <replacement-expression-if-null>
       ] //null值或不存在的会被设置为数组最后一个表达式的值
    
    $switch: {
       branches: [
          { case: <expression>, then: <expression> },
          { case: <expression>, then: <expression> },
          ...
       ],
       default: <expression>
    } //整个表达式作为一个值返回
    
    #数据类型方法
    $convert:
          {
             input: <expression>,
             to: <type expression>,
             onError: <expression>,  // Optional.
             onNull: <expression>    // Optional.
          }
    $type: <expression> //字段不存在时返回'missing'
    
    #基本聚合
    $min: <expression>
    $max: <expression> 
    $avg: <expression> 
    $sum: <expression>字段数值数组,或者[ <expression1>, <expression2> ... ]每个字段为数值,不能混合
    
    #其他:...

    分页

    sort({}).skip().limit()

    修改

    基本方法,参考:https://docs.mongodb.com/manual/reference/update-methods/

    db.collection.update(
       <query>,
       <update>,
       {
         upsert: <boolean>,
         multi: <boolean>,
         writeConcern: <document>,
         collation: <document>,
         arrayFilters: [ <filterdocument1>, ... ],
         hint:  <document|string>, // Added in MongoDB 4.2
         let: <document> // Added in MongoDB 5.0
       }
    )
    db.collection.updateOne(<filter>, <update>, <options>)
    db.collection.updateMany(<filter>, <update>, <options>)
    db.collection.replaceOne(<filter>, <update>, <options>)

    单元属性,参考:https://docs.mongodb.com/manual/reference/operator/update/

    //普通字段
    $inc,$mul
    $min,$max
    $set,$unset,$setOnInsert
    $rename
    
    //数组类型
    $ //代表数组中的一个元素
    $[],$[identifier] //代表数组每个元素
    $push,$each,$position,$addToSet
    $pop,$pull,$pullAll
    $slice,$sort
  • 相关阅读:
    【模板小程序】链表排序(qsort/insert_sort/merge_sort)
    链表回文判断(C++)
    【模板小程序】十进制大数除法(输出商和余数)
    【模板小程序】字符串截取
    【模板小程序】翻转一个句子中的单词
    web前端基础背景
    MongoDB基本知识(补充)
    Python-ORM
    Python-元编程
    ElementUI 中 el-table 获取当前选中行的index
  • 原文地址:https://www.cnblogs.com/tkzc2013/p/14982540.html
Copyright © 2020-2023  润新知