欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

mongodb命令行連接及基礎(chǔ)命令總結(jié)大全

 更新時(shí)間:2024年04月17日 09:52:18   作者:最后一支迷迭香  
大家可能平時(shí)在開(kāi)發(fā)過(guò)程中都使用客戶(hù)端工具來(lái)連接和查詢(xún)mongodb,但是一般生產(chǎn)當(dāng)中的數(shù)據(jù)庫(kù)是不允許本地客戶(hù)端連接的,下面這篇文章主要給大家介紹了關(guān)于mongodb命令行連接及基礎(chǔ)命令總結(jié)的相關(guān)資料,需要的朋友可以參考下

一、命令行連接到mongodb

我們先來(lái)簡(jiǎn)單的看一下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有非常多的參數(shù),下面我們演示幾個(gè)比較常用的參數(shù)來(lái)測(cè)試連接mongo連接到mongodb命令

  • –host為遠(yuǎn)程服務(wù)器地址及端口
  • -u為用戶(hù)名
  • -p為密碼
mongosh --host localhost:27017 -u root -p 'yourpassword'

如果沒(méi)有密碼可直接使用

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.

二、基礎(chǔ)命令

2.1 數(shù)據(jù)庫(kù)操作

查看所有數(shù)據(jù)庫(kù)

show dbs

查看當(dāng)前所屬數(shù)據(jù)庫(kù)

db

切換數(shù)據(jù)庫(kù)或創(chuàng)建數(shù)據(jù)庫(kù)(存在則切換,不存在則創(chuàng)建)

use 數(shù)據(jù)庫(kù)名

刪除數(shù)據(jù)庫(kù)

db.dropDatabase()

2.2 集合的基礎(chǔ)命令

不手動(dòng)創(chuàng)建集合:

  • 向不存在的集合中第一次加入數(shù)據(jù)時(shí),集合會(huì)被創(chuàng)建出來(lái)

手動(dòng)創(chuàng)建集合:

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

  • 參數(shù)crapped:默認(rèn)值為false表示不設(shè)置上限,值為true表示設(shè)置上限
  • 參數(shù)size:當(dāng)capped值為true時(shí),需要指定此參數(shù),表示上限大小,當(dāng)文檔達(dá)到上限時(shí),會(huì)將之前的數(shù)據(jù)覆蓋,單位為字節(jié)

查看集合:

show collections

刪除結(jié)合:

db.集合名稱(chēng).drop()

2.3 插入

db.集合名稱(chēng).insert(document)

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

插入文檔時(shí),如果不指定_id參數(shù),MongoDB會(huì)為文檔分配一個(gè)唯一的Objectid

2.4 保存

db.集合名稱(chēng).save(document)

如果文檔的_id已經(jīng)存在則修改,如果文檔的_id不存在則添加

2.5 查詢(xún)

方法 find() 查詢(xún)?nèi)?/p>

	db.集合名稱(chēng).find({條件文檔})
	db.stu.find({name:'zhangsan'})

方法 findOne() 查詢(xún)只返回一個(gè)

    db.集合名稱(chēng).findOne({條件文檔})
    db.stu.findOne({age:20})

方法 pretty() 將結(jié)果格式化

    db.集合名稱(chēng).find({條件文檔}).pretty()
    db.stu.find({name:'zhangsan'}).pretty()

2.6 更新

db.集合名稱(chēng).update(,,{multi:})

1. 參數(shù)query:查詢(xún)條件

2. 參數(shù)update:更新操作符

3. 參數(shù)multi:可選,默認(rèn)是false,表示只更新找到的第一條記錄,值為true表示把滿(mǎn)足條件的文檔全部更新

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

2.7 刪除

db.集合名稱(chēng).remove(, {justOne:})

1. 參數(shù)query:可選,刪除文檔的條件

2. 參數(shù)justOne:可選,如果設(shè)為true或1,則只刪除一條,默認(rèn)為false,表示刪除多條

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

2.8 比較運(yùn)算符

等于:默認(rèn)是等于判斷,沒(méi)有運(yùn)算符

小于: 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 范圍運(yùn)算符

使用 “ i n " , " in", " in","nin” 判斷是否在某個(gè)范圍內(nèi)

查詢(xún)年齡為18、28的學(xué)生

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

2.10 邏輯運(yùn)算符

and:在json中寫(xiě)多個(gè)條件即可

查詢(xún)年齡大于或等于18,并且性別為1的學(xué)生

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

or:使用 “$or” ,值為數(shù)組,數(shù)組中每個(gè)元素為json

查詢(xún)年齡大于18,或性別為1的學(xué)生

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

查詢(xún)年齡大于18,或性別為1的學(xué)生,并且姓名是xiaoming

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

2.11 正則表達(dá)式

使用 // 或 $regex 編寫(xiě)正則表達(dá)式

查詢(xún)姓小的學(xué)生

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

2.12 limit和skip()

方法limit():用于讀取指定數(shù)量的文檔

db.集合名稱(chēng).find().limit(number)

查詢(xún)2條學(xué)生信息

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

方法skip():用于跳過(guò)指定數(shù)量的文檔

db.集合名稱(chēng).find().skip(number)

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

同時(shí)使用

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

2.13 排序

方法 sort() 用于對(duì)集合進(jìn)行排列

db.集合名稱(chēng).find().sort({字段:1,…})

  • 參數(shù) 1 為升序排列
  • 參數(shù) -1 位降序排列

根據(jù)性別降序,再根據(jù)年齡升序

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

2.14 統(tǒng)計(jì)個(gè)數(shù)

方法 count() 用于統(tǒng)計(jì)結(jié)果集中文檔條數(shù)

db.集合名稱(chēng).find({條件}).count()

db.集合名稱(chēng).count({條件})

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

2.15 消除重復(fù)

方法 distinct() 對(duì)數(shù)據(jù)進(jìn)行去重

db.集合名稱(chēng).distinct(‘去重字段’,{條件})

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

三、聚合函數(shù)操作

3.1常用管道

在mongodb中,文檔處理完畢后,通過(guò)管道進(jìn)行下一次處理

常用的管道如下:

  • $group:將集合中的文檔分組,可用于統(tǒng)計(jì)結(jié)果
  • $match:過(guò)濾數(shù)據(jù),只輸出符合條件的文檔
  • $project:修改輸入文檔的結(jié)構(gòu),如重命名、增加、刪除字段、創(chuàng)建計(jì)算結(jié)果
  • $sort:講輸入文檔排序后輸出
  • $limit:限制聚合管道返回的文檔數(shù)
  • $skip:跳過(guò)指定數(shù)量的文檔。并返回余下的文檔
  • $unwind:將數(shù)組類(lèi)型的字段進(jìn)行拆分

3.2 表達(dá)式

常用表達(dá)式:

  • $sum:計(jì)算總和, $sum:1 表示以一倍計(jì)算
  • $avg:計(jì)算平均值
  • $min:獲取最小值
  • $max:獲取最大值
  • $push:在結(jié)果文檔中插入值到一個(gè)數(shù)組中
  • $first:根據(jù)資源文檔的排序獲取第一個(gè)文檔數(shù)據(jù)
  • $last:根據(jù)資源文檔的排序獲取最后一個(gè)文檔數(shù)據(jù)

3.3 $group

將集合中的文檔分組,可用于統(tǒng)計(jì)結(jié)果

_id表示分組的依據(jù),使用某個(gè)字段的格式為’$字段’

統(tǒng)計(jì)地區(qū)總數(shù)

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

將集合中所有文檔分為一組:求學(xué)生的總?cè)藬?shù)和平均年齡

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

3.4 $project

查詢(xún)學(xué)生的姓名、年齡

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

查詢(xún)男生、女生人數(shù),輸出人數(shù)

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

3.5 $match

用于過(guò)去數(shù)據(jù),只輸出符合條件的文檔

查詢(xún)年齡大于20的學(xué)生

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

查詢(xún)你哪里大于20的男生、女生總數(shù)

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

3.6 $sort

將輸入文檔排序后輸出

查詢(xún)學(xué)生信息,并按年齡升序

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

按照性別分類(lèi)并按人數(shù)降序

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

3.7 $limit

限制聚合管道返回的文檔數(shù)

查詢(xún)2條學(xué)生信息

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

3.8 $skip

跳過(guò)指定數(shù)量的文檔,并返回余下的文檔

查詢(xún)從第2條開(kāi)始的學(xué)生信息

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

3.9 $unwind

將文檔中的某一個(gè)數(shù)組類(lèi)型字段拆分成多條,每條包含數(shù)組中的一個(gè)值

語(yǔ)法:db.集合名稱(chēng).aggregate({ u n w i n d : ′ unwind:' unwind:′字段名稱(chēng)’})

db.t2.insert(
   {_id:1, item:'t-shirt', size:['S', 'M', 'L']}
)
db.t2.aggregate(
   {$unwind:'$size'}
)
注意:如果每條文檔中含有該數(shù)組的字段值為空的時(shí)候,想保留字段內(nèi)容,可以使用:
db.t2.aggregate(
   {$unwind:{
       path: '$字段名稱(chēng)',
       preserveNullAndEmptyArrays:<boolean>  # 防止數(shù)據(jù)丟失
   }}
)

總結(jié) 

到此這篇關(guān)于mongodb命令行連接及基礎(chǔ)命令總結(jié)的文章就介紹到這了,更多相關(guān)mongodb命令行連接基礎(chǔ)命令內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • MongoDB安裝圖文教程

    MongoDB安裝圖文教程

    這篇文章主要為大家詳細(xì)介紹了MongoDB安裝圖文教程,分為兩大部分為大家介紹下載MongoDB和安裝MongoDB的方法,感興趣的小伙伴們可以參考一下
    2016-07-07
  • Mongodb解決不能連接到服務(wù)器的錯(cuò)誤問(wèn)題

    Mongodb解決不能連接到服務(wù)器的錯(cuò)誤問(wèn)題

    這篇文章主要介紹了Mongodb解決不能連接到服務(wù)器的錯(cuò)誤問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • 關(guān)于NoSQL之MongoDB的一些總結(jié)

    關(guān)于NoSQL之MongoDB的一些總結(jié)

    這篇文章主要介紹了關(guān)于NoSQL之MongoDB的一些總結(jié)的相關(guān)資料,需要的朋友可以參考下
    2015-07-07
  • mongodb增量/全量備份腳本的實(shí)現(xiàn)詳解

    mongodb增量/全量備份腳本的實(shí)現(xiàn)詳解

    這篇文章主要給大家介紹了關(guān)于mongodb增量/全量備份腳本的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2018-09-09
  • MongoDB整庫(kù)備份與還原以及單個(gè)collection備份、恢復(fù)方法

    MongoDB整庫(kù)備份與還原以及單個(gè)collection備份、恢復(fù)方法

    mongodb數(shù)據(jù)庫(kù)維護(hù)離不開(kāi)必要的備份、恢復(fù)操作,而且一般不會(huì)出錯(cuò),所以我們?cè)谑褂玫臅r(shí)候大部分時(shí)候使用備份和恢復(fù)操作就可以了
    2013-08-08
  • 詳解linux 使用docker安裝mongodb方法

    詳解linux 使用docker安裝mongodb方法

    這篇文章主要介紹了linux 使用docker安裝mongodb方法,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11
  • MongoDB 副本集的搭建過(guò)程

    MongoDB 副本集的搭建過(guò)程

    這篇文章主要介紹了MongoDB 副本集的搭建過(guò)程,幫助大家更好的理解和學(xué)習(xí)使用MongoDB數(shù)據(jù)庫(kù),感興趣的朋友可以了解下
    2021-03-03
  • MongoDB連接數(shù)據(jù)庫(kù)并創(chuàng)建數(shù)據(jù)等使用方法

    MongoDB連接數(shù)據(jù)庫(kù)并創(chuàng)建數(shù)據(jù)等使用方法

    MongoDB?是一個(gè)介于關(guān)系數(shù)據(jù)庫(kù)和非關(guān)系數(shù)據(jù)庫(kù)之間的產(chǎn)品,是非關(guān)系數(shù)據(jù)庫(kù)當(dāng)中功能最豐富,最像關(guān)系數(shù)據(jù)庫(kù)的。接下來(lái)通過(guò)本文給大家介紹MongoDB連接數(shù)據(jù)庫(kù)并創(chuàng)建數(shù)據(jù)等使用方法,感興趣的朋友一起看看吧
    2021-11-11
  • MongoDB對(duì)數(shù)組進(jìn)行增刪改查操作

    MongoDB對(duì)數(shù)組進(jìn)行增刪改查操作

    與關(guān)系型數(shù)據(jù)庫(kù)相比,MongoDB支持?jǐn)?shù)組,將數(shù)組存儲(chǔ)到文檔之中,下面這篇文章主要給大家介紹了關(guān)于MongoDB對(duì)數(shù)組進(jìn)行增刪改查操作的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-05-05
  • MongoDB數(shù)據(jù)庫(kù)性能監(jiān)控詳解

    MongoDB數(shù)據(jù)庫(kù)性能監(jiān)控詳解

    MongoDB作為圖片和文檔的存儲(chǔ)數(shù)據(jù)庫(kù),為啥不直接存MySQL里,還要搭個(gè)MongoDB集群,麻不麻煩?這篇文章就帶你介紹MongoDB數(shù)據(jù)庫(kù)性能監(jiān)控,感興趣的同學(xué)可以參考閱讀
    2023-03-03

最新評(píng)論