mongodb 命令行连接及基础命令
大家可能平时在开发过程中都使用客户端工具来连接和查询mongodb,但是一般生产当中的数据库是不允许本地客户端连接的。
本文主要讲解了如何通过命令行的方式连接到mongodb的服务端,并使用一些简单的查询语句
文章目录
- 一、命令行连接到mongodb
- 二、基础命令
- 2.1 数据库操作
- 2.2 集合的基础命令
- 2.3 插入
- 2.4 保存
- 2.5 查询
- 2.6 更新
- 2.7 删除
- 2.8 比较运算符
- 2.9 范围运算符
- 2.10 逻辑运算符
- 2.11 正则表达式
- 2.12 limit和skip()
- 2.13 排序
- 2.14 统计个数
- 2.15 消除重复
- 三、聚合函数操作
- 3.1常用管道
- 3.2 表达式
- 3.3 $group
- 3.4 $project
- 3.5 $match
- 3.6 $sort
- 3.7 $limit
- 3.8 $skip
- 3.9 $unwind
一、命令行连接到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: http://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: http://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> # 防止数据丢失
}}
)