暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

五、MongoDB 常用命令

我的技术人生 2021-05-11
630

1、客户端连接

    mongo 127.0.0.1:27017
    或者 直接执行以下命令也可以
    mongo


    # 显示以下信息说明连接成功 
    MongoDB shell version v4.4.5
    connecting to: mongodb://127.0.0.1:27017/test?compressors=disabled&gssapiServiceName=mongodb
    Implicit session: session { "id" : UUID("f78e815b-1ba8-4d5a-9852-5a870193a878") }
    MongoDB server version: 4.4.5
    Welcome to the MongoDB shell.
    For interactive help, type "help".
    For more comprehensive documentation, see
    https://docs.mongodb.com/
    Questions? Try the MongoDB Developer Community Forums
      https://community.mongodb.com


    2、数据库


    2.1、显示所有数据库
      > show dbs;
      admin 0.000GB
      config 0.000GB
      local 0.000GB
      yzfile  8.931GB


      2.2、创建/选择数据库
        > use yzfile;
        switched to db yzfile


        # 说明 如果数据库yzfile存在,则切换;否则,创建一个yzfile数据库;
        # 新创建的数据库,如果没有数据的话,那么通过show dbs 是不会显示的;


        2.3、显示当前所在的数据库
          > db
          mytest


          2.4、删除数据库
            > db.dropDatabase()
            { "dropped" : "mytest", "ok" : 1 }


            3、集合


            3.1、集合创建说明

            语法: db.createCollection(name, options)

            参数说明:

             。name: 要创建的集合名称

             。options:可选参数,指定有关内存大小及索引的选项;


            字段类型
            描述
            capped
            布尔
            (可选)如果为true,则创建固定集合。

            固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。

            当该值为true时,必须指定size参数。

            autoIndexId
            布尔(可选)如果为true,自动在_id 字段创建索引。默认为false, 3.2 之后不再支持该参数。
            size
            数值
            (可选)为固定集合指定最大值(以字节计算)。如果capped为true,则需要指定该字段
            max
            数值
            (可选)指定固定集合中包含文档的最大数量


            说明:在插入文档时,MongoDB优先检查固定集合的size字段,然后检查max字段。


            3.2、 创建集合

              > db.createCollection('coll1');
              { "ok" : 1 }
                > db.createCollection('coll2', {'capped':true, 'size':1024});
                { "ok" : 1 }


                3.3、查看所有集合

                  > show collections;
                  coll1
                  coll2
                    > show tables;
                    coll2

                    说明, show collections 和 show tables 都可以


                    3.4、删除集合

                    语法:db.collection_name.drop()

                      > db.coll1.drop();
                      true


                      4、文档


                      4.1、创建文档

                      语法:db.collection_name.insert(document)

                      说明:collection_name 存在则插入;不存在,则会先创建一个文档。

                        > db.coll2.insert({title: 'MongoDB 教程',
                        ...  description: 'MongoDB 是一个 分布式 数据库',
                        ...  by: '我的技术人生',
                        ...  url: 'http://www.myitlife.com',
                        ...  tags: ['mongodb', 'database', 'NoSQL'],
                        ...  likes: 100
                        ... });
                        WriteResult({ "nInserted" : 1 })


                        还可以指定插入的条数

                          db.collection.insertOne():向指定集合中插入一条文档数据
                          db.collection.insertMany():向指定集合中插入多条文档数据


                          4.2、文档查询


                          查询所有

                            > db.coll2.find();
                            { "_id" : ObjectId("6086cf8f8ce6acb29c15132d"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 分布式 数据库", "by" : "我的技术人生", "url" : "http://www.myitlife.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
                            { "_id" : ObjectId("6086d0e28ce6acb29c15132e"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 分布式 数据库", "by" : "我的技术人生", "url" : "http://www.myitlife.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 120 }
                            { "_id" : ObjectId("6086d1388ce6acb29c15132f"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 分布式 数据库", "by" : "我的技术人生", "url" : "http://www.myitlife.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 150 }
                            { "_id" : ObjectId("6086d1778ce6acb29c151330"), "title" : "MongoDB 学习", "description" : "MongoDB 是一个 分布式 数据库", "by" : "我的技术人生", "url" : "http://www.myitlife.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 200 }


                            条件查询,查询 title 为 MongoDB 教程的所有数据

                              > db.coll2.find({'title':'MongoDB 学习'});
                              { "_id" : ObjectId("6086d1778ce6acb29c151330"), "title" : "MongoDB 学习", "description" : "MongoDB 是一个 分布式 数据库", "by" : "我的技术人生", "url" : "http://www.myitlife.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 200 }


                              以易读方式查询

                                > db.mycollection.find().pretty();
                                {
                                "_id" : ObjectId("6086cf3c8ce6acb29c15132c"),
                                "title" : "MongoDB 教程",
                                "description" : "MongoDB 是一个 分布式 数据库",
                                  "by" : "我的技术热恒",
                                  "url" : "http://www.myitlife.com",
                                "tags" : [
                                "mongodb",
                                "database",
                                "NoSQL"
                                ],
                                  "likes" : 110
                                }



                                4.3、删除文档

                                语法:

                                db.collection.remove(
                                <query>,
                                {
                                justOne: <boolean>,
                                writeConcern: <document>
                                }

                                )


                                没有指定capped可以直接删除

                                  > db.coll1.remove({'likes':201});
                                  WriteResult({ "nRemoved" : 1 })


                                  如果集合的capped为true的话, 那么是不能直接删除的,可以直接删除集合

                                    > db.coll2.remove({'likes':120});
                                    WriteResult({
                                    "nRemoved" : 0,
                                    "writeError" : {
                                    "code" : 20,
                                    "errmsg" : "cannot remove from a capped collection: db_test.coll2"
                                    }
                                    })



                                    4.4、查询文档是否指定capped

                                      > db.mycollection.isCapped();
                                      false
                                      >
                                      > db.coll2.isCapped();
                                      true


                                      4.5、指定查询行数 limit(num)

                                        > db.coll2.find({}).pretty().limit(2);
                                        {
                                        "_id" : ObjectId("6086cf8f8ce6acb29c15132d"),
                                        "title" : "MongoDB 教程",
                                        "description" : "MongoDB 是一个 分布式 数据库",
                                        "by" : "我的技术人生",
                                        "url" : "http://www.myitlife.com",
                                        "tags" : [
                                        "mongodb",
                                        "database",
                                        "NoSQL"
                                        ],
                                        "likes" : 100
                                        }
                                        {
                                        "_id" : ObjectId("6086d0e28ce6acb29c15132e"),
                                        "title" : "MongoDB 教程",
                                        "description" : "MongoDB 是一个 分布式 数据库",
                                        "by" : "我的技术人生",
                                        "url" : "http://www.myitlife.com",
                                        "tags" : [
                                        "mongodb",
                                        "database",
                                        "NoSQL"
                                        ],
                                        "likes" : 120
                                        }


                                        4.6、跳过指定行 skip(num)

                                          > db.coll2.find({}).pretty().limit(2).skip(1);
                                          {
                                          "_id" : ObjectId("6086d0e28ce6acb29c15132e"),
                                          "title" : "MongoDB 教程",
                                          "description" : "MongoDB 是一个 分布式 数据库",
                                          "by" : "我的技术人生",
                                          "url" : "http://www.myitlife.com",
                                          "tags" : [
                                          "mongodb",
                                          "database",
                                          "NoSQL"
                                          ],
                                          "likes" : 120
                                          }
                                          {
                                          "_id" : ObjectId("6086d1388ce6acb29c15132f"),
                                          "title" : "MongoDB 教程",
                                          "description" : "MongoDB 是一个 分布式 数据库",
                                          "by" : "我的技术人生",
                                          "url" : "http://www.myitlife.com",
                                          "tags" : [
                                          "mongodb",
                                          "database",
                                          "NoSQL"
                                          ],
                                          "likes" : 150
                                          }

                                          说明:查询两条,跳过索引为1的数据;skip 默认是0;



                                          4.7、排序(降序、升序) sort

                                          语法:db.collection.find().sort({key:1})

                                            # 根据likes升序
                                            > db.coll2.find({}).sort({'likes':1});
                                            { "_id" : ObjectId("6086cf8f8ce6acb29c15132d"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 分布式 数据库", "by" : "我的技术人生", "url" : "http://www.myitlife.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
                                            { "_id" : ObjectId("6086d0e28ce6acb29c15132e"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 分布式 数据库", "by" : "我的技术人生", "url" : "http://www.myitlife.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 120 }
                                            { "_id" : ObjectId("6086d1388ce6acb29c15132f"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 分布式 数据库", "by" : "我的技术人生", "url" : "http://www.myitlife.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 150 }
                                            { "_id" : ObjectId("6086d1778ce6acb29c151330"), "title" : "MongoDB 学习", "description" : "MongoDB 是一个 分布式 数据库", "by" : "我的技术人生", "url" : "http://www.myitlife.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 200 }


                                            # 根据likes降序
                                            > db.coll2.find({}).sort({'likes':-1});
                                            { "_id" : ObjectId("6086d1778ce6acb29c151330"), "title" : "MongoDB 学习", "description" : "MongoDB 是一个 分布式 数据库", "by" : "我的技术人生", "url" : "http://www.myitlife.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 200 }
                                            { "_id" : ObjectId("6086d1388ce6acb29c15132f"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 分布式 数据库", "by" : "我的技术人生", "url" : "http://www.myitlife.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 150 }
                                            { "_id" : ObjectId("6086d0e28ce6acb29c15132e"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 分布式 数据库", "by" : "我的技术人生", "url" : "http://www.myitlife.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 120 }
                                            { "_id" : ObjectId("6086cf8f8ce6acb29c15132d"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 分布式 数据库", "by" : "我的技术人生", "url" : "http://www.myitlife.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }




                                            5、索引


                                            5.1、创建索引

                                            语法:

                                                3.0.0 之前版本 db.collection.ensureIndex() 

                                                3.0.0 之后版本 db.collection.createIndex() 


                                                db.collection.createIndex(keys, options)


                                              > db.coll2.createIndex({'likes':1});
                                              {
                                              "createdCollectionAutomatically" : false,
                                              "numIndexesBefore" : 1,
                                              "numIndexesAfter" : 2,
                                              "ok" : 1
                                              }

                                              说明:keys 是要添加的索引, 1代表升序, -1 代表降序;也创建联合索引。


                                              5.2、查看集合中的索引

                                                > db.coll2.getIndexes();
                                                [
                                                {
                                                "v" : 2,
                                                "key" : {
                                                "_id" : 1
                                                },
                                                "name" : "_id_"
                                                },
                                                {
                                                "v" : 2,
                                                "key" : {
                                                "likes" : 1
                                                },
                                                "name" : "likes_1"
                                                }
                                                ]



                                                5.3、查看集合索引大小

                                                  > db.coll2.totalIndexSize();
                                                  57344


                                                  5.5、删除索引


                                                  删除指定索引

                                                    > db.coll2.dropIndex('likes_1');
                                                    { "nIndexesWas" : 2, "ok" : 1 }


                                                    删除所有索引

                                                      > db.col.dropIndexes()



                                                      6、聚合查询


                                                      关于MongoDB中的聚合查询的说明,

                                                        MongoDB 中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。
                                                        有点类似 SQL 语句中的 count(*)。MongoDB中聚合的方法使用aggregate()。
                                                        基本语法:
                                                        >db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)


                                                        我们先来看下MongoDB中的聚合跟MySql的查询对比:

                                                        MongoDB
                                                        SQL操作描述实例
                                                        $groupgroup by 分组db.mycol.aggregate([{$group : {_id : "$by_user", snum : {$sum : "$likes"}}}])
                                                        $sum

                                                        count()

                                                        sum() 

                                                        计算总和db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])
                                                        $avgavg() 计算平均值db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])
                                                        $minmin()获取集合中所有文档对应值的最小值db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}])
                                                        $maxmax() 获取集合中所有文档对应值的最大值db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}])
                                                        $match

                                                        where

                                                        having

                                                        查询条件
                                                        $sortorder by
                                                        排序
                                                        $limitlimit取条数db.mycol.aggregate( { $limit:5} )
                                                        $projectselect
                                                        选择db.mycol.aggregate( [ {$project :{_id:0,name:1,city:1}  } ] )

                                                        $lookup 

                                                        (v3.2 新增)

                                                        join
                                                        连接db.mycol.update({},{$set:{sex:1}},{multi:1})
                                                        $pushinsert
                                                        插入
                                                        db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])


                                                        文章转载自我的技术人生,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

                                                        评论