mongodb命令行连接及基础命令总结大全

 更新时间:2024年04月17日 09:52:18   作者:最后一支迷迭香  
大家可能平时在开发过程中都使用客户端工具来连接和查询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>  # 防止数据丢失
   }}
)

总结 

到此这篇关于mongodb命令行连接及基础命令总结的文章就介绍到这了,更多相关mongodb命令行连接基础命令内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 如何利用MongoDB存储Docker日志详解

    如何利用MongoDB存储Docker日志详解

    这篇文章主要给大家介绍了关于如何利用MongoDB存储Docker日志的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友没呢下面随着小编来一起学习学习吧
    2018-09-09
  • mongodb3.4集群搭建实战之高可用的分片+副本集

    mongodb3.4集群搭建实战之高可用的分片+副本集

    这篇文章主要给大家介绍了关于mongodb3.4集群搭建实战之高可用的分片+副本集的相关资料,文中通过示例代码将实现的步骤一步步的介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面跟着小编来一起学习学习吧。
    2017-08-08
  • mongodb与sql关系型数据比较

    mongodb与sql关系型数据比较

    今天小编就为大家分享一篇关于mongodb与sql关系型数据比较,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • Mongodb 3.2.9开启用户权限认证问题的步骤详解

    Mongodb 3.2.9开启用户权限认证问题的步骤详解

    这篇文章主要给大家介绍了关于Mongodb 3.2.9开启用户权限认证问题的详细步骤,通过开启权限认证,会对大家的Mongodb更加保护的安全些,文中将步骤介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-08-08
  • mongodb 实现远程连接

    mongodb 实现远程连接

    这篇文章主要介绍了mongodb 实现远程连接,需要的朋友可以参考下
    2014-07-07
  • MongoDB数据库基础知识整理

    MongoDB数据库基础知识整理

    这篇文章介绍了MongoDB数据库的基础知识,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • MongoDB用Mongoose得到的对象不能增加属性完美解决方法(两种)

    MongoDB用Mongoose得到的对象不能增加属性完美解决方法(两种)

    本文给大家分享两种解决方案解决MongoDB用Mongoose得到的对象不能增加属性问题,本文给大家介绍的非常详细,需要的朋友参考下吧
    2017-11-11
  • MongoDB Shell常用基本操作命令详解

    MongoDB Shell常用基本操作命令详解

    这篇文章主要为大家介绍了MongoDB Shell常用基本操作命令详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-12-12
  • 深究从MongoDB的ObjectId中获取时间信息

    深究从MongoDB的ObjectId中获取时间信息

    MongoDB默认使用_id字段作为主键,类型为ObjectId。ObjectId的生成有一定的规则,详情可以查看这篇文章MongoDB深究之ObjectId
    2017-03-03
  • mongoDB4.0数据库的操作方法

    mongoDB4.0数据库的操作方法

    这篇文章主要介绍了mongoDB4.0数据库的操作方法及注意事项,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-10-10

最新评论