mongodb 命令行连接及基础命令

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: mongodb 命令行连接及基础命令

大家可能平时在开发过程中都使用客户端工具来连接和查询mongodb,但是一般生产当中的数据库是不允许本地客户端连接的。

本文主要讲解了如何通过命令行的方式连接到mongodb的服务端,并使用一些简单的查询语句


一、命令行连接到mongodb

我们先来简单的看一下mongosh命令:

root@bddff4197a79:/# mongosh --help
  $ mongosh [options] [db address] [file names (ending in .js or .mongodb)]
  Options:
    -h, --help                                 Show this usage information
    -f, --file [arg]                           Load the specified mongosh script
        --host [arg]                           Server to connect to
        --port [arg]                           Port to connect to
        --version                              Show version information
        --verbose                              Increase the verbosity of the output of the shell
        --quiet                                Silence output from the shell during the connection process
        --shell                                Run the shell after executing files
        --nodb                                 Don't connect to mongod on startup - no 'db address' [arg] expected
        --norc                                 Will not run the '.mongoshrc.js' file on start up
        --eval [arg]                           Evaluate javascript
        --retryWrites                          Automatically retry write operations upon transient network errors
  Authentication Options:
    -u, --username [arg]                       Username for authentication
    -p, --password [arg]                       Password for authentication
        --authenticationDatabase [arg]         User source (defaults to dbname)
        --authenticationMechanism [arg]        Authentication mechanism
        --awsIamSessionToken [arg]             AWS IAM Temporary Session Token ID
        --gssapiServiceName [arg]              Service name to use when authenticating using GSSAPI/Kerberos
        --sspiHostnameCanonicalization [arg]   Specify the SSPI hostname canonicalization (none or forward, available on Windows)
        --sspiRealmOverride [arg]              Specify the SSPI server realm (available on Windows)
  TLS Options:
        --tls                                  Use TLS for all connections
        --tlsCertificateKeyFile [arg]          PEM certificate/key file for TLS
        --tlsCertificateKeyFilePassword [arg]  Password for key in PEM file for TLS
        --tlsCAFile [arg]                      Certificate Authority file for TLS
        --tlsAllowInvalidHostnames             Allow connections to servers with non-matching hostnames
        --tlsAllowInvalidCertificates          Allow connections to servers with invalid certificates
        --tlsCertificateSelector [arg]         TLS Certificate in system store (Windows and macOS only)
        --tlsCRLFile [arg]                     Specifies the .pem file that contains the Certificate Revocation List
        --tlsDisabledProtocols [arg]           Comma separated list of TLS protocols to disable [TLS1_0,TLS1_1,TLS1_2]
  API version options:
        --apiVersion [arg]                     Specifies the API version to connect with
        --apiStrict                            Use strict API version mode
        --apiDeprecationErrors                 Fail deprecated commands for the specified API version
  FLE Options:
        --awsAccessKeyId [arg]                 AWS Access Key for FLE Amazon KMS
        --awsSecretAccessKey [arg]             AWS Secret Key for FLE Amazon KMS
        --awsSessionToken [arg]                Optional AWS Session Token ID
        --keyVaultNamespace [arg]              database.collection to store encrypted FLE parameters
        --kmsURL [arg]                         Test parameter to override the URL of the KMS endpoint
  DB Address Examples:
        foo                                    Foo database on local machine
        192.168.0.5/foo                        Foo database on 192.168.0.5 machine
        192.168.0.5:9999/foo                   Foo database on 192.168.0.5 machine on port 9999
        mongodb://192.168.0.5:9999/foo         Connection string URI can also be used
  File Names:
        A list of files to run. Files must end in .js and will exit after unless --shell is specified.
  Examples:
        Start mongosh using 'ships' database on specified connection string:
        $ mongosh mongodb://192.168.0.5:9999/ships
  For more information on usage: https://docs.mongodb.com/mongodb-shell.

可以看到mongosh有非常多的参数,下面我们演示几个比较常用的参数来测试连接mongo

连接到mongodb命令

  • –host为远程服务器地址及端口
  • -u为用户名
  • -p为密码
mongosh --host localhost:27017 -u root -p 'yourpassword'

如果没有密码可直接使用

mongosh --host localhost:27017

demo:

root@bddff4197a79:/# mongosh --host localhost:27017
Current Mongosh Log ID: 654b58d5a9821e4d7bbbf493
Connecting to:    mongodb://localhost:27017/?directConnection=true&serverSelectionTimeoutMS=2000
Using MongoDB:    5.0.5
Using Mongosh:    1.1.6
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
------
   The server generated these startup warnings when booting:
   2023-11-08T01:13:10.562+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
   2023-11-08T01:13:11.610+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------
Warning: Found ~/.mongorc.js, but not ~/.mongoshrc.js. ~/.mongorc.js will not be loaded.
  You may want to copy or rename ~/.mongorc.js to ~/.mongoshrc.js.

二、基础命令

2.1 数据库操作

查看所有数据库

show dbs

查看当前所属数据库

db

切换数据库或创建数据库(存在则切换,不存在则创建)

use 数据库名

删除数据库

db.dropDatabase()

2.2 集合的基础命令

不手动创建集合:

向不存在的集合中第一次加入数据时,集合会被创建出来

手动创建集合:

db.createCollection(name, options)

db.createCollection(“stu”)

db.createCollection(“stb”, {capped:true, size:10})

参数crapped:默认值为false表示不设置上限,值为true表示设置上限

参数size:当capped值为true时,需要指定此参数,表示上限大小,当文档达到上限时,

会将之前的数据覆盖,单位为字节

查看集合:

show collections

删除结合:

db.集合名称.drop()

2.3 插入

db.集合名称.insert(document)

db.stu.insert({name:'zhangsan', gender:1})
db.stu.insert({_id:"20170101", name:'zhangsan', gender:1})

插入文档时,如果不指定_id参数,MongoDB会为文档分配一个唯一的Objectid

2.4 保存

db.集合名称.save(document)

如果文档的_id已经存在则修改,如果文档的_id不存在则添加

2.5 查询

方法 find() 查询全部

db.集合名称.find({条件文档})
  db.stu.find({name:'zhangsan'})

方法 findOne() 查询只返回一个

db.集合名称.findOne({条件文档})
    db.stu.findOne({age:20})

方法 pretty() 将结果格式化

db.集合名称.find({条件文档}).pretty()
    db.stu.find({name:'zhangsan'}).pretty()

2.6 更新

db.集合名称.update(,,{multi:})

1. 参数query:查询条件

2. 参数update:更新操作符

3. 参数multi:可选,默认是false,表示只更新找到的第一条记录,值为true表示把满足条件的文档全部更新

db.stu.update({name:'zhangsan', {name:'wangwu'}}) 更新匹配的第一条,其他值会被删除
    db.stu.update({name:'zhangsan', {$set:{name:'hys'}}}) 更新匹配的第一条,其他值不会被删除
    db.stu.update{{}, {$set:{gender:0}}, {multi:true}} 跟新全部,其他值不会被删除

2.7 删除

db.集合名称.remove(, {justOne:})

1. 参数query:可选,删除文档的条件

2. 参数justOne:可选,如果设为true或1,则只删除一条,默认为false,表示删除多条

db.stu.remove({name:'wangwu'}, {justOne:true}) 删除一条
  db.stu.remove({gender:2}) 删除全部

2.8 比较运算符

等于:默认是等于判断,没有运算符

小于:l t ( l e s s t h a n ) 小于等于: lt (less than) 小于等于:lt(lessthan)小于等于:lte (less than equal)

大于:g t ( g r e a t e r t h a n ) 大于等于: gt (greater than) 大于等于:gt(greaterthan)大于等于:gte (greater than equal)

不等于:$ne (not equal)

db.stu.find({age: {$gte:18}})

2.9 范围运算符

使用 “i n " , " in", "in","nin” 判断是否在某个范围内

查询年龄为18、28的学生

db.stu.find({age:{$in:[18,28]}})

2.10 逻辑运算符

and:在json中写多个条件即可

查询年龄大于或等于18,并且性别为1的学生

db.stu.find({age:{$gte:18}, sex:1})

or:使用 “$or” ,值为数组,数组中每个元素为json

查询年龄大于18,或性别为1的学生

db.stu.find({$or:[{age:{$gt:18}}, {sex:1}]})

查询年龄大于18,或性别为1的学生,并且姓名是xiaoming

db.stu.find({$or:[{age:{$gt:18}}, {set:1}],name:'xiaoming'})

2.11 正则表达式

使用 // 或 $regex 编写正则表达式

查询姓小的学生

db.stu.find({name:/^xiao/})
db.stu.find({name:{$regex:'^xiao'}})

2.12 limit和skip()

方法limit():用于读取指定数量的文档

db.集合名称.find().limit(number)

查询2条学生信息

db.stu.find().limit(2)

方法skip():用于跳过指定数量的文档

db.集合名称.find().skip(number)

db.stu.find().skip(2)

同时使用

db.stu.find().limit(1).skip(2)
db.stu.find().limit(2).skip(1)

2.13 排序

方法 sort() 用于对集合进行排列

db.集合名称.find().sort({字段:1,…})

参数 1 为升序排列

参数 -1 位降序排列

根据性别降序,再根据年龄升序

db.stu.find().sort({sex:-1,age:1})

2.14 统计个数

方法 count() 用于统计结果集中文档条数

db.集合名称.find({条件}).count()

db.集合名称.count({条件})

db.stu.find({sex:1}).count()
db.stu.count({age:{$gt:20},sex:1})

2.15 消除重复

方法 distinct() 对数据进行去重

db.集合名称.distinct(‘去重字段’,{条件})

db.stu.distinct('sex', {age: {$gt:18}})

三、聚合函数操作

3.1常用管道

在mongodb中,文档处理完毕后,通过管道进行下一次处理

常用的管道如下:

$group:将集合中的文档分组,可用于统计结果

$match:过滤数据,只输出符合条件的文档

$project:修改输入文档的结构,如重命名、增加、删除字段、创建计算结果

$sort:讲输入文档排序后输出

$limit:限制聚合管道返回的文档数

$skip:跳过指定数量的文档。并返回余下的文档

$unwind:将数组类型的字段进行拆分

3.2 表达式

常用表达式:

$sum:计算总和, $sum:1 表示以一倍计算

$avg:计算平均值

$min:获取最小值

$max:获取最大值

$push:在结果文档中插入值到一个数组中

$first:根据资源文档的排序获取第一个文档数据

$last:根据资源文档的排序获取最后一个文档数据

3.3 $group

将集合中的文档分组,可用于统计结果

_id表示分组的依据,使用某个字段的格式为’$字段’

统计地区总数

db.map.aggregate(
    {$group:{_id: '$country',counter: {$sum:1}}}
)

将集合中所有文档分为一组:求学生的总人数和平均年龄

db.stu.aggregate(
    {$group:{_id: null , counter: {$sum:1},age_avg: {$avg: '$age'}}}
)

3.4 $project

查询学生的姓名、年龄

db.stu.aggregate(
   {$project:{_id:0,name:1,age:1}}
)

查询男生、女生人数,输出人数

db.stu.aggregate(
   {$group:{_id:'$sex',counter:{$sum:1}}},
   {$project:{_id:0, sex:'$_id',counter:1}}
)

3.5 $match

用于过去数据,只输出符合条件的文档

查询年龄大于20的学生

db.stu.aggregate(
   {$match:{age:{$gt:20}}}
)

查询你哪里大于20的男生、女生总数

db.stu.aggregate(
   {$match:{age:{$gt:20}}},
   {$group:{_id:'$sex', counter:{$sum:1}}}
)

3.6 $sort

将输入文档排序后输出

查询学生信息,并按年龄升序

db.stu.aggregate(
    {$sort:{age:1}}
)

按照性别分类并按人数降序

db.stu.aggregate(
    {$group:{_id:'$sex',count:{$sum:1}}},
    {$sort:{count:-1}},
    {$project:{count:1,_id:0}})

3.7 $limit

限制聚合管道返回的文档数

查询2条学生信息

db.stu.aggregate(
   {$limit:2}
)

3.8 $skip

跳过指定数量的文档,并返回余下的文档

查询从第2条开始的学生信息

db.stu.aggregate(
   {$skip:2}
)

3.9 $unwind

将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值

语法:db.集合名称.aggregate({u n w i n d : ′ unwind:'unwind:字段名称’})

db.t2.insert(
   {_id:1, item:'t-shirt', size:['S', 'M', 'L']}
)
db.t2.aggregate(
   {$unwind:'$size'}
)
注意:如果每条文档中含有该数组的字段值为空的时候,想保留字段内容,可以使用:
db.t2.aggregate(
   {$unwind:{
       path: '$字段名称',
       preserveNullAndEmptyArrays:<boolean>  # 防止数据丢失
   }}
)
相关文章
|
7月前
|
NoSQL MongoDB 微服务
微服务——MongoDB常用命令——文档的分页查询
本文介绍了文档分页查询的相关内容,包括统计查询、分页列表查询和排序查询。统计查询使用 `count()` 方法获取记录总数或按条件统计;分页查询通过 `limit()` 和 `skip()` 方法实现,控制返回和跳过的数据量;排序查询利用 `sort()` 方法,按指定字段升序(1)或降序(-1)排列。同时提示,`skip()`、`limit()` 和 `sort()` 的执行顺序与编写顺序无关,优先级为 `sort()` &gt; `skip()` &gt; `limit()`。
251 1
|
7月前
|
JSON NoSQL MongoDB
微服务——MongoDB常用命令——文档基本CRUD
本文介绍了MongoDB中文档的基本操作,包括插入、查询、更新和删除。单个文档插入使用`insert()`或`save()`方法,批量插入用`insertMany()`。查询所有文档用`find()`,条件查询可在`find()`中添加参数,投影查询控制返回字段。更新文档通过`update()`实现,支持覆盖修改、局部修改(使用`$set`)和批量修改。列值增长可用`$inc`实现。删除文档用`remove()`,需谨慎操作以免误删数据。此外,文档键值对有序,区分大小写,不能有重复键。
137 1
|
7月前
|
存储 NoSQL MongoDB
微服务——MongoDB常用命令——MongoDB索引知识概述
本文介绍MongoDB索引相关知识,包括其在查询中的重要作用。索引可避免全集合扫描,显著提升查询效率,尤其在处理海量数据时。通过B树数据结构存储字段值并排序,支持相等匹配、范围查询及排序操作。文中还提供了官方文档链接以供深入学习。
100 0
|
7月前
|
存储 NoSQL MongoDB
微服务——MongoDB常用命令——MongoDB索引的类型
本节介绍了MongoDB中索引的几种类型及其特点。包括单字段索引,支持升序/降序排序,索引顺序对操作无影响;复合索引,字段顺序重要,可实现多级排序;地理空间索引,支持平面与球面几何查询;文本索引,用于字符串搜索并存储词根;哈希索引,基于字段值散列,适合等值匹配但不支持范围查询。
180 1
微服务——MongoDB常用命令——MongoDB索引的类型
|
7月前
|
存储 JSON NoSQL
MongoDB常用命令
本文介绍了将文章评论数据存储到MongoDB中的操作方法,包括数据库和集合的基本操作。主要内容涵盖:选择与创建数据库(如`articledb`)、数据库删除、集合的显式与隐式创建及删除、文档的CRUD操作(插入、查询、更新、删除)。此外,还详细说明了分页查询、排序查询以及统计查询的方法,例如使用`limit()`、`skip()`实现分页,`sort()`进行排序,`count()`统计记录数。通过实例展示了如何高效管理MongoDB中的数据。
|
7月前
|
NoSQL 关系型数据库 MongoDB
微服务——MongoDB常用命令——集合操作
本节主要介绍MongoDB中的集合操作,包括显式与隐式创建集合的方法。显式创建使用`db.createCollection(name)`,需遵循命名规范(如不能以&quot;system.&quot;开头或包含`\0`字符)。隐式创建则通过直接向不存在的集合插入文档实现,更为常用。此外,还介绍了集合删除方法`db.collection.drop()`及其返回值规则,帮助用户管理数据库中的集合资源。
241 0
|
7月前
|
存储 NoSQL MongoDB
微服务——MongoDB常用命令1——数据库操作
本节介绍了 MongoDB 中数据库的选择、创建与删除操作。使用 `use 数据库名称` 可选择或创建数据库,若数据库不存在则自动创建。通过 `show dbs` 或 `show databases` 查看所有可访问的数据库,用 `db` 命令查看当前数据库。注意,集合仅在插入数据后才会真正创建。数据库命名需遵循 UTF-8 格式,避免特殊字符,长度不超过 64 字节,且部分名称如 `admin`、`local` 和 `config` 为系统保留。删除数据库可通过 `db.dropDatabase()` 实现,主要用于移除已持久化的数据库。
442 0
|
7月前
|
存储 NoSQL Linux
微服务2——MongoDB单机部署4——Linux系统中的安装启动和连接
本节主要介绍了在Linux系统中安装、启动和连接MongoDB的详细步骤。首先从官网下载MongoDB压缩包并解压至指定目录,接着创建数据和日志存储目录,并配置`mongod.conf`文件以设定日志路径、数据存储路径及绑定IP等参数。之后通过配置文件启动MongoDB服务,并使用`mongo`命令或Compass工具进行连接测试。此外,还提供了防火墙配置建议以及服务停止的两种方法:快速关闭(直接杀死进程)和标准关闭(通过客户端命令安全关闭)。最后补充了数据损坏时的修复操作,确保数据库的稳定运行。
451 0
|
7月前
|
NoSQL JavaScript Shell
微服务2——MongoDB单机部署2——Shell连接
本节介绍如何通过Shell连接MongoDB数据库,使用`mongo`命令登录,默认连接本地127.0.0.1的27017端口。可查看数据库列表(`show databases`),退出shell(`exit`),或通过`--help`获取更多参数。MongoDB Shell基于JavaScript解释器,支持运行JS程序。
171 0
|
11月前
|
存储 JSON NoSQL
MongoDB常用命令
MongoDB常用命令
101 1
MongoDB常用命令

推荐镜像

更多