本次介紹,基於mongdb 4.2版本。
一、配置mongo Shell
- 自定義提示
- 使用mongo Shell中的外部編輯器
- 更改mongo Shell批處理大小
1.自定義提示
可以通過在mongo shell中設置變量提示來修改提示的內容。prompt變量可以保存字符串和JavaScript代碼。如果prompt包含一個返回字符串的函數,mongo可以在每個提示中顯示動態信息。
可以在.mongorc.js文件中添加提示邏輯,以便在每次啓動mongo shell時設置提示。
1.1 自定義提示符來顯示操作的數量
要創建包含當前會話中發出的操作數的mongo shell提示符,需要在mongo shell中定義以下變量:
cmdCount = 1;
prompt = function() {
return (cmdCount++) + "> ";
}
提示符將類似於以下內容:
1>
2>
3>
例:
1.2 自定義提示以顯示數據庫和主機名
要以<database>@<hostname>$的形式創建mongo shell提示,請定義以下變量:
host = db.serverStatus().host;
prompt = function() {
return db+"@"+host+"$ ";
}
提示符將類似於以下內容:
test@myHost1$
例:
1.3 自定義提示符來顯示運行時間和文檔數量
要創建包含系統運行時間和當前數據庫中的文檔數量的mongo shell提示符,請在mongo shell中定義以下提示變量:
prompt = function() {
return "Uptime:"+db.serverStatus().uptime+" Documents:"+db.stats().objects+" > ";
}
提示符將類似於以下內容:
Uptime:5897 Documents:6 >
例:
2. 使用mongo Shell中的外部編輯器
可以在啓動mongo shell之前設置編輯器環境變量,從而在mongo shell中使用自己的編輯器。
export EDITOR=vim
mongo
進入mongo shell後,您可以通過輸入edit <variable>或edit <function>來使用指定的編輯器進行編輯,如下面的示例所示:
a.定義一個函數myFunction:
function myFunction () { }
b.使用編輯器編輯函數:
edit myFunction
該命令應該打開vim編輯會話。完成編輯後,保存並退出vim編輯會話。
c.在mongo shell中,輸入myFunction來查看函數定義:
myFunction
結果應該是從你保存的修改:
function myFunction() {
print("This was edited");
}
提示:當mongo shell解釋在外部編輯器中編輯的代碼時,它可能修改函數中的代碼,這取決於JavaScript編譯器。例如,mongo可以將1+1轉換爲2或刪除註釋。實際的更改隻影響代碼的外觀,並且會根據所使用的JavaScript版本而有所不同,但不會影響代碼的語義。
3.更改mongo Shell批處理大小
find()方法是從集合中檢索文檔的JavaScript方法。find()方法返回結果的遊標;但是,在mongo shell中,如果沒有使用var關鍵字將返回的遊標分配給變量,那麼遊標將自動迭代20次,以打印與查詢匹配的前20個文檔。mongo shell將提示鍵入它,以再次迭代20次。
可以設置DBQuery.shellBatchSize屬性將文檔數量從默認值20更改爲10,如下面的例子所示:
DBQuery.shellBatchSize = 10;
例:
輸入"it"顯示其它:
我們設置顯示的個數後:
提示:重啓服務後,設置失效。
二、訪問mongo Shell幫助
本節將展示以下幾點:
除了MongoDB手冊中的文檔外,mongo shell還在其“在線”幫助系統中提供了一些額外的信息。本文檔提供了訪問此幫助信息的概述。
1.命令行幫助
要查看啓動mongo shell的選項和幫助列表,請使用命令行中的--help選項:
mongo --help
2.Shell Help
要查看幫助列表,在mongo shell中,鍵入help:
help
3.Database Help
a.要查看服務器上的數據庫列表,請使用show dbs命令:
show dbs
show databases是show dbs的別名。
b.要查看可以在db對象上使用的方法的幫助列表,請調用db.help()方法:
db.help()
c.要查看shell中方法的實現,請鍵入db.<方法名>,不帶括號(()),如下面的例子所示,它將返回方法db.updateUser()的實現:
db.updateUser
提示:如果部署使用訪問控制運行,則操作根據用戶權限返回不同的值。有關詳細信息,請參見listDatabases Behavior行爲。
4.Collection Help
a.要查看當前數據庫中的集合列表,請使用show collections命令:
show collections
b.要查看集合對象上可用方法的幫助(例如db.<collection>),請使用db.<collection>.help()方法:
db.collection.help()
<collection>可以是一個存在的集合的名稱,儘管您可以指定一個不存在的集合。
c.要查看集合方法的實現,請鍵入db.<collection>.<method> name without the圓括號(()),如下面的例子所示,它將返回save()方法的實現:
db.collection.save
提示:如何插入的是數組列表,在代碼中是批量插入。
5.Cursor Help
當您使用mongo shell中的find()方法執行讀操作時,您可以使用各種遊標方法來修改find()行爲,並使用各種JavaScript方法來處理find()方法返回的遊標。
a.要列出可用的修飾符和遊標處理方法,請使用db.collection.find().help()命令:
db.collection.find().help()
<collection>可以是一個存在的集合的名稱,儘管您可以指定一個不存在的集合。
b.要查看遊標方法的實現,請鍵入db.<collection>.find().<method> name without the圓括號(()),如下面的例子所示,它將返回toArray()方法的實現:
db.collection.find().toArray
處理遊標的一些有用方法如下:
- hasNext()檢查遊標是否有更多的文檔要返回。
- next()返回下一個文檔並將光標向前移動1。
- forEach(<function>)迭代整個遊標,並將<function>應用於遊標返回的每個文檔。函數>需要一個單獨的參數,該參數對應於每個迭代的文檔。
有關迭代遊標和從遊標檢索文檔的示例,請參閱 cursor handling。有關所有可用的遊標方法,請參見Cursor。
6.Wrapper Object Help
要獲得mongo shell中可用的包裝器類的列表,如BinData(),請在mongo shell中鍵入help misc:
help misc
三、爲mongo Shell編寫腳本
本節介紹以下幾點:
- 打開新連接
- 交互式和mongo腳本之間的區別
- 腳本
可以用JavaScript爲mongo shell編寫腳本,以便在MongoDB中操作數據或執行管理操作。
本教程介紹如何編寫使用mongo shell訪問MongoDB的JavaScript。
1.打開新連接
在mongo shell或JavaScript文件中,可以使用mongo()構造函數實例化數據庫連接:
new Mongo()
new Mongo(<host>)
new Mongo(<host:port>)
考慮下面的示例,它實例化了一個到MongoDB實例的新連接,該連接在默認端口的本地主機上運行,並使用getDB()方法將全局db變量設置爲myDatabase:
conn = new Mongo();
db = conn.getDB("myDatabase");
如果連接到實施訪問控制的MongoDB實例,則可以使用db.auth()方法進行身份驗證。
另外,可以使用connect()方法連接到MongoDB實例。下面的示例連接到在本地主機上運行的MongoDB實例,並使用非默認端口27020設置全局db變量:
db = connect("localhost:27020/myDatabase");
2.交互式和腳本蒙戈之間的區別
提示:從4.2版開始,mongo shell提供了 isInteractive()
方法,該方法返回一個布爾值,指示mongo shell是在交互模式還是腳本模式下運行。
true:交互式
在爲mongo shell編寫腳本時,請考慮以下幾點:
- 要設置db全局變量,請使用getDB()方法或connect()方法。可以將數據庫引用分配給db之外的變量。
- mongo shell中的寫操作默認使用{w: 1}的寫關注點。如果執行批量操作,請使用bulk()方法。有關更多信息,請參見寫入方法確認。
- 您不能在JavaScript文件中使用任何shell幫助程序(例如使用<dbname>, show dbs等),因爲它們不是有效的JavaScript。
下表將最常見的mongo shell幫助程序映射到對應的JavaScript。
Shell Helpers | JavaScript Equivalents |
---|---|
show dbs , show databases |
db.adminCommand('listDatabases') |
use <db> |
db = db.getSiblingDB('<db>') |
show collections |
db.getCollectionNames() |
show users |
db.getUsers() |
show roles |
db.getRoles({showBuiltinRoles: true}) |
show log <logname> |
db.adminCommand({ 'getLog' : '<logname>' }) |
show logs |
db.adminCommand({ 'getLog' : '*' }) |
it |
cursor = db.collection.find() if ( cursor.hasNext() ){ cursor.next(); } |
- 在交互模式下,mongo打印操作的結果,包括所有遊標的內容。在腳本中,可以使用JavaScript print()函數,也可以使用返回格式化JSON的mongo特定printjson()函數。
要在mongo shell腳本中打印結果遊標中的所有項目,請使用以下習語:
cursor = db.collection.find();
while ( cursor.hasNext() ) {
printjson( cursor.next() );
}
3.腳本
在系統提示中,使用mongo來評估JavaScript。
--eval
option
使用--eval選項mongo傳遞一個JavaScript片段給shell,如下圖所示:
mongo test --eval "printjson(db.getCollectionNames())"
這將返回db.getCollectionNames()的輸出,使用mongo shell連接到本地主機接口上端口27017上運行的mongod或mongos實例。
3.1.執行JavaScript文件
可以爲mongo shell指定一個.js文件,mongo將直接執行JavaScript。考慮下面的例子:
mongo localhost:27017/test myjsfile.js
此操作在mongo shell中執行myjsfile.js腳本,該腳本連接到mongod實例上的測試數據庫,通過端口27017上的localhost接口進行訪問。
另外,可以使用Mongo()構造函數在javascript文件中指定mongodb連接參數。有關更多信息,請參見打開新連接。
可以使用load()函數從mongo shell中執行.js文件,如下所示:
load("myjstest.js")
這個函數加載並執行myjste .js文件。
:load()方法接受相對路徑和絕對路徑。如果mongo shell的當前工作目錄是/data/db,並且myjste .js駐留在/data/db/scripts目錄中,那麼在mongo shell中進行以下調用是等價的:
load("scripts/myjstest.js")
load("/data/db/scripts/myjstest.js")
提示:load()函數沒有搜索路徑。如果所需的腳本不在當前工作目錄或完整的指定路徑中,mongo將無法訪問該文件。
四、mongo Shell中的數據類型
本節將介紹以下內容:
MongoDB BSON支持JSON之外的其他數據類型。驅動程序在宿主語言中爲這些數據類型提供本地支持,mongo shell還提供了幾個幫助類來支持在mongo JavaScript shell中使用這些數據類型。有關其他信息,請參閱擴展JSON引用。
1.類型
1.1 日期
mongo shell提供了各種方法來返回日期,可以是字符串,也可以是日期對象:
- Date(),該方法將返回當前日期的字符串。
- new Date()構造函數,它使用ISODate()包裝器返回一個日期對象。
- ISODate()構造函數,使用ISODate()包裝器返回一個日期對象。
在內部,日期對象存儲爲一個有符號的64位整數,表示自Unix紀元(1970年1月1日)以來的毫秒數。
並不是所有的數據庫操作和驅動程序都支持完整的64位範圍。您可以安全地處理從0到9999範圍內的日期和年份。
1.1.1 以字符串形式返回日期
要將日期作爲字符串返回,請使用date()方法,如下面的示例所示:
var myDateString = Date();
要打印變量的值,請在shell中鍵入變量名,如下所示:
myDateString
結果是myDateString的值:
Wed Dec 19 2012 01:03:25 GMT-0500 (EST)
要驗證類型,請使用typeof操作符,如下所示:
typeof myDateString
操作返回字符串。
1.1.2 返回日期
mongo shell使用ISODate助手包裝日期類型的對象;但是,對象仍然是Date類型。
下面的示例使用新的Date()構造函數和ISODate()構造函數來返回日期對象。
var myDate = new Date();
var myDateInitUsingISODateWrapper = ISODate();
您也可以將新的操作符與ISODate()構造函數一起使用。
要打印變量的值,請在shell中鍵入變量名,如下所示:
myDate
結果是包裝在ISODate()幫助程序中的myDate的日期值:
ISODate("2012-12-19T06:01:17.171Z")
要驗證類型,請使用instanceof操作符,如下所示:
myDate instanceof Date
myDateInitUsingISODateWrapper instanceof Date
這兩個操作都返回true。
1.2 ObjectId
mongo shell圍繞ObjectId數據類型提供了ObjectId()包裝器類。要生成新的ObjectId,請在mongo shell中使用以下操作:
new ObjectId
1.3 NumberLong
默認情況下,mongo shell將所有數字都視爲浮點值。mongo shell提供NumberLong()包裝器來處理64位整數。
NumberLong()包裝器接受long作爲字符串:
NumberLong("2090845886852")
下面的例子使用NumberLong()包裝器來寫入集合:
db.collection.insertOne( { _id: 10, calc: NumberLong("2090845886852") } )
db.collection.updateOne( { _id: 10 },
{ $set: { calc: NumberLong("2555555000000") } } )
db.collection.updateOne( { _id: 10 },
{ $inc: { calc: NumberLong(5) } } )
a.檢索文件以驗證:
db.collection.findOne( { _id: 10 } )
b.在返回的文檔中,calc字段包含一個NumberLong對象:
{ "_id" : 10, "calc" : NumberLong("2555555000005") }
如果使用$inc將包含NumberLong對象的字段的值增加一個浮點數,則數據類型將更改爲一個浮點數,如下面的示例所示:
a.使用$inc將calc字段增加5,mongo shell將其視爲一個浮點數:
db.collection.updateOne( { _id: 10 },
{ $inc: { calc: 5 } } )
b.檢索更新後的文件:
db.collection.findOne( { _id: 10 } )
c.在更新的文檔中,calc字段包含一個浮點值:
{ "_id" : 10, "calc" : 2555555000010 }
1.4 NumberInt
默認情況下,mongo shell將所有數字都視爲浮點值。mongo shell提供NumberInt()構造函數來顯式地指定32位整數。
1.5 NumberDecimal
新版本3.4。
mongo shell默認將所有數字視爲64位浮點雙精度值。mongo shell提供NumberDecimal()構造函數來顯式指定128位的基於小數的浮點值,這些浮點值能夠精確模擬十進制舍入。此功能適用於處理貨幣數據(如金融、稅務和科學計算)的應用程序。
decimal BSON類型使用IEEE 754 decimal128浮點編號格式,該格式支持34位小數(即有效數字),指數範圍爲−6143到+6144。
NumberDecimal()構造函數接受decimal值作爲字符串:
NumberDecimal("1000.55")
該值存儲在數據庫中如下:
NumberDecimal("1000.55")
NumberDecimal()構造函數也接受來自mongo shell的雙精度值(即不帶引號),但由於存在丟失精度的風險,不建議這樣做。構造函數創建基於二進制的雙精度參數表示(可能會丟失精度),然後將該值轉換爲精度爲15位的十進制值。下面的示例以雙精度值的形式隱式傳遞該值,並演示如何創建精度爲15位的值:
NumberDecimal(1000.55)
該值存儲在數據庫中,如下所示:
NumberDecimal("1000.55000000000")
下面的示例以雙精度值的形式隱式傳遞該值,並展示了精度損失是如何發生的:
NumberDecimal (9999999.4999999999)
該值存儲在數據庫中如下:
NumberDecimal("9999999.50000000")
下面的示例以雙精度值的形式隱式傳遞該值,並展示了精度損失是如何發生的:
NumberDecimal(9999999.4999999999)
該值存儲在數據庫中如下:
NumberDecimal("9999999.50000000")
提示:要在MongoDB驅動程序中使用decimal數據類型,請確保使用支持它的驅動程序版本。
1.6 相等與排序順序
十進制類型的值將根據其實際數值與其他數字類型進行比較和排序。基於二進制的雙類型的數值通常具有基於小數的數值的近似表示,並且可能不完全等於它們的十進制表示,因此在檢查十進制值的相等性時,請使用NumberDecimal()構造函數。考慮以下例子與以下文件的數字收集:
{ "_id" : 1, "val" : NumberDecimal( "9.99" ), "description" : "Decimal" }
{ "_id" : 2, "val" : 9.99, "description" : "Double" }
{ "_id" : 3, "val" : 10, "description" : "Double" }
{ "_id" : 4, "val" : NumberLong(10), "description" : "Long" }
{ "_id" : 5, "val" : NumberDecimal( "10.0" ), "description" : "Decimal" }
當將來自下表的查詢插入到db.numbers.find(<query>)方法中時,將返回以下結果:
Query | Results |
---|---|
{ “val”: 9.99 } | { “_id”: 2, “val”: 9.99, “description”: “Double” } |
{ “val”: NumberDecimal( “9.99” ) } | { “_id”: 1, “val”: NumberDecimal( “9.99” ), “description”: “Decimal” } |
{ val: 10 } |
{ “_id”: 3, “val”: 10, “description”: “Double” } { “_id”: 4, “val”: NumberLong(10), “description”: “Long” } { “_id”: 5, “val”: NumberDecimal( “10.0” ), “description”: “Decimal” } |
{ val: NumberDecimal( “10” ) } |
{ “_id”: 3, “val”: 10, “description”: “Double” } { “_id”: 4, “val”: NumberLong(10), “description”: “Long” } { “_id”: 5, “val”: NumberDecimal( “10.0” ), “description”: “Decimal” } |
第一個查詢{“val”:9.99}隱式地搜索9.99的雙表示形式,它不等於該值的小數表示形式。
構造函數NumberDecimal()用於查詢十進制表示爲9.99的文檔。double類型的值被排除,因爲它們與十進制表示的9.99的精確值不匹配。
在查詢整數時,將返回所有數字類型的匹配值。例如,查詢10的雙表示將在結果中包含10.0的十進制表示,反之亦然。
1.7 decimal
類型檢查
要測試十進制類型,請使用字符串別名“decimal”或十進制類型的數字代碼19的$type操作符。
db.inventory.find( { price: { $type: "decimal" } } )
2.Check Types in the mongo
Shell
爲了確定字段的類型,mongo shell提供了instanceof和typeof操作符。
2.1 instanceof
instanceof返回一個布爾值來測試一個值是否是某個類型的實例。
例如,下面的操作測試_id字段是否是ObjectId類型的實例:
mydoc._id instanceof ObjectId
操作返回true.
2.2 typeof
typeof返回字段的類型。
例如,下面的操作返回_id字段的類型:
typeof mydoc._id
在這種情況下,typeof將返回更一般的對象類型,而不是ObjectId類型。
五、mongo Shell快速參考
mongo
Shell Command History- Command Line Options
- Command Helpers
- Basic Shell JavaScript Operations
- Keyboard Shortcuts
- Queries
- Error Checking Methods
- Administrative Command Helpers
- Opening Additional Connections
- Miscellaneous
- Additional Resources
1.mongo Shell命令歷史
您可以使用向上和向下箭頭鍵檢索mongo shell中發出的以前的命令。命令歷史記錄存儲在~/中.dbshell文件。有關更多信息,請參見 .dbshell。
2.命令行參數
mongo shell可以從多個選項開始。有關所有可用選項的詳細信息,請參閱mongo外殼頁。
下表顯示了一些常見的mongo選項:
Option | Description |
---|---|
--help |
Show command line options |
--nodb |
Start To connect later, see Opening New Connections. |
--shell |
Used in conjunction with a JavaScript file (i.e. <file.js>) to continue in the See JavaScript file for an example. |
3.Command Helpers
mongo shell提供了各種幫助。下表顯示了一些常用的幫助方法和命令:
Help Methods and Commands | Description |
---|---|
help |
Show help. |
db.help() |
Show help for database methods. |
db.<collection>.help() |
Show help on collection methods. The <collection> can be the name of an existing collection or a non-existing collection. |
show dbs |
Print a list of all databases on the server. The operation corresponds to the |
use <db> |
Switch current database to <db> . The mongo shell variable db is set to the current database. |
show collections |
Print a list of all collections for current database. SEE ALSO |
show users |
Print a list of users for current database. |
show roles |
Print a list of all roles, both user-defined and built-in, for the current database. |
show profile |
Print the five most recent operations that took 1 millisecond or more. See documentation on the database profiler for more information. |
show databases |
Print a list of all available databases. The operation corresponds to the |
load() |
Execute a JavaScript file. See Write Scripts for the mongo Shell for more information. |
4.基本的Shell JavaScript操作
mongo shell爲數據庫操作提供了一個JavaScript API。
在mongo shell中,db是引用當前數據庫的變量。變量自動設置爲默認數據庫測試,或者在使用use <db>切換當前數據庫時設置。
下表顯示了一些常見的JavaScript操作:
JavaScript Database Operations | Description |
---|---|
db.auth() |
If running in secure mode, authenticate the user. |
coll = db.<collection> |
Set a specific collection in the current database to a variable coll = db.myCollection; You can perform operations on the coll.find(); |
db.collection.find() |
Find all documents in the collection and returns a cursor. See the See Iterate a Cursor in the mongo Shell for information on cursor handling in the |
db.collection.insertOne() |
Insert a new document into the collection. |
db.collection.insertMany() |
Insert multiple new documents into the collection. |
db.collection.updateOne() |
Update a single existing document in the collection. |
db.collection.updateMany() |
Update multiple existing documents in the collection. |
db.collection.save() |
Insert either a new document or update an existing document in the collection. |
db.collection.deleteOne() |
Delete a single document from the collection. |
db.collection.deleteMany() |
Delete documents from the collection. |
db.collection.drop() |
Drops or removes completely the collection. |
db.collection.createIndex() |
Create a new index on the collection if the index does not exist; otherwise, the operation has no effect. |
db.getSiblingDB() |
Return a reference to another database using this same connection without explicitly switching the current database. This allows for cross database queries. |
5.Keyboard Shortcuts
mongo shell提供了與bash shell或Emacs中類似的大多數鍵盤快捷鍵。對於一些函數,mongo提供了多個鍵綁定,以適應幾個熟悉的範例。
下表列舉了mongo shell支持的按鍵:
6.Queries
在mongo shell中,使用find()和findOne()方法執行讀操作。
find()方法返回一個遊標對象,mongo shell迭代該對象以在屏幕上打印文檔。默認情況下,mongo打印前20個。mongo shell將提示用戶“鍵入它”以繼續迭代接下來的20個結果。
下表提供了一些常見的讀操作在mongo shell:
Read Operations | Description |
---|---|
db.collection.find(<query>) |
查找集合中與<query>條件匹配的文檔。如果<query>條件未指定或爲空。 read操作選擇集合中的所有文檔。 coll = db.users; coll.find( { name: "Joe" } ); 有關指定<query>條件的更多信息,請參見 Specify Equality Condition. |
db.collection.find(<query>, <projection>) |
查找與<query>條件匹配的文檔,並僅返回<projection>中的特定字段。 coll = db.users; coll.find( { }, { name: true } ); For more information on specifying the |
db.collection.find().sort(<sort order>) |
返回指定的<排序順序>的結果。 coll = db.users; coll.find().sort( { name: 1 } ); |
db.collection.find(<query>).sort(<sort order>) |
返回與指定的<sort order>中的<query>條件匹配的文檔。 |
db.collection.find( ... ).limit( <n> ) |
將結果限制爲<n>行。強烈建議您只需要一定數量的行就可以獲得最佳性能。 |
db.collection.find( ... ).skip( <n> ) |
Skip <n> results. |
db.collection.count() |
返回集合中的文檔總數。 |
db.collection.find(<query>).count() |
返回與查詢匹配的文檔總數。 |
db.collection.findOne(<query>) |
查找並返回單個文檔。如果沒有找到,則返回null。 coll = db.users; coll.findOne( { name: "Joe" } ); Internally, the |
有關更多信息和示例,請參見 Query Documents文檔。請參閱 Query and Projection Operators操作符以指定其他查詢操作符。
7.錯誤檢查方法
mongo shell寫方法將寫關注點直接集成到方法執行中,並返回一個WriteResult()對象,該對象包含操作的結果,包括任何寫錯誤和寫關注點錯誤。
8.Administrative Command Helpers
下表列出了一些支持數據庫管理的常用方法:
JavaScript Database Administration Methods | Description |
---|---|
db.fromColl.renameCollection(<toColl>) |
將集合從fromColl重命名爲<toColl>。 See Naming Restrictions. |
db.getCollectionNames() |
獲取當前數據庫中所有集合的列表。 |
db.dropDatabase() |
除當前數據庫。 |
有關方法的完整列表,請參見administrative database methods。
9.打開額外的連接
可以在mongo shell中創建新的連接。
下表顯示了創建連接的方法:
db = connect("<host><:port>/<dbname>") |
打開一個新的數據庫連接。 |
conn = new Mongo() db = conn.getDB("dbname") |
使用新Mongo()打開到新服務器的連接。 使用連接的getDB()方法來選擇數據庫。 |
有關從mongo shell打開新連接的更多信息,請參見 Opening New Connections。
10.Miscellaneous
下表顯示了一些雜項方法:
Object.bsonsize(<document>) 以字節爲單位打印<文檔>的 BSON大小
11.Additional Resources
參考之前的文檔。