面试官喜欢常问的MongoDB常用命令及操作

~

面试官喜欢常问的MongoDB常用命令及操作


大家可能平时在开发过程中都使用客户端工具来连接和查询mongodb,但是一般生产当中的数据库是不允许本地客户端连接的。本文主要讲解了如何通过命令行的方式连接到mongodb的服务端,并使用一些常见的的查询语句


首先我们先对MongoDB做一个简单的介绍

MongoDB是一个基于分布式文件存储的数据库,使用C++语言编写。它旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB介于关系数据库和非关系数据库之间,是非关系数据库当中功能最丰富、最像关系数据库的。

MongoDB将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB文档类似于JSON对象,字段值可以包含其他文档、数组及文档数组。它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。

MongoDB最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。

此外,MongoDB还具有以下特点:

  1. 面向集合存储,易存储对象类型的数据。

  2. 模式自由。

  3. 支持动态查询。

  4. 支持完全索引,包含内部对象。

  5. 支持查询。

  6. 支持复制和故障恢复。

  7. 使用高效的二进制数据存储,包括大型对象(如视频等)。

  8. 自动处理碎片,以支持云计算层次的扩展性。

  9. 可通过网络访问。

在高负载情况下,添加更多的节点可以保证服务器性能。MongoDB也易于部署和使用,存储数据非常方便。

总的来说,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()

不手动创建集合:向不存在的集合中第一次加入数据时,集合会被创建出来手动创建集合: 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(<query>,<update>,{multi:<boolean>})    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(<query>, {justOne:<boolean>})    1. 参数query:可选,删除文档的条件    2. 参数justOne:可选,如果设为true或1,则只删除一条,默认为false,表示删除多条

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

2.8 比较运算符

等于:默认是等于判断,没有运算符小于:$lt (less than)小于等于:$lte (less than equal)大于:$gt (greater than)大于等于:$gte (greater than equal)不等于:$ne (not equal)

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

2.9 范围运算符

使用 “$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({$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去试试~


END


面试官喜欢常问的MongoDB常用命令及操作


PS便




Java面向容错编程之重试机制

因为开发同学的失误造成DB没存上数据,我总结的补救措施

朋友拿我总结的锁优化去面试,工资涨了10k

为什么要使用 refresh_token 来刷新token?

【Java】和面试官谈策略模式

面试官喜欢常问的MongoDB常用命令及操作

面试官喜欢常问的MongoDB常用命令及操作

面试官喜欢常问的MongoDB常用命令及操作

原文始发于微信公众号(最后一支迷迭香):面试官喜欢常问的MongoDB常用命令及操作

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

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/201321.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!