当前位置: 代码网 > it编程>数据库>Nosql > mongodb命令行连接及基础命令总结大全

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

2024年05月26日 Nosql 我要评论
一、命令行连接到mongodb我们先来简单的看一下mongosh命令:root@bddff4197a79:/# mongosh --help $ mongosh [options] [db addr

一、命令行连接到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命令行连接基础命令内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com