天天看點

MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

本次介紹,基于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>
           

例:

MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

1.2 自定義提示以顯示資料庫和主機名

要以<database>@<hostname>$的形式建立mongo shell提示,請定義以下變量:

host = db.serverStatus().host;

prompt = function() {
             return db+"@"+host+"$ ";
         }
           

提示符将類似于以下内容:

[email protected]$
           

例:

MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

1.3 自定義提示符來顯示運作時間和文檔數量

要建立包含系統運作時間和目前資料庫中的文檔數量的mongo shell提示符,請在mongo shell中定義以下提示變量:

prompt = function() {
           return "Uptime:"+db.serverStatus().uptime+" Documents:"+db.stats().objects+" > ";
         }
           

提示符将類似于以下内容:

Uptime:5897 Documents:6 >
           

例:

MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

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;
           

例:

MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

輸入"it"顯示其它:

MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

我們設定顯示的個數後:

MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

提示:重新開機服務後,設定失效。

二、通路mongo Shell幫助

本節将展示以下幾點:

  • Command Line Help
  • Shell Help
  • Database Help
  • Collection Help
  • Cursor Help
  • Wrapper Object Help

除了MongoDB手冊中的文檔外,mongo shell還在其“線上”幫助系統中提供了一些額外的資訊。本文檔提供了通路此幫助資訊的概述。

1.指令行幫助

要檢視啟動mongo shell的選項和幫助清單,請使用指令行中的--help選項:

mongo --help
           

2.Shell Help

要檢視幫助清單,在mongo shell中,鍵入help:

help
           
MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

3.Database Help

    a.要檢視伺服器上的資料庫清單,請使用show dbs指令:

show dbs
           

    show databases是show dbs的别名。

    b.要檢視可以在db對象上使用的方法的幫助清單,請調用db.help()方法:

db.help()
           
MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

    c.要檢視shell中方法的實作,請鍵入db.<方法名>,不帶括号(()),如下面的例子所示,它将傳回方法db.updateUser()的實作:

db.updateUser
           
MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

提示:如果部署使用通路控制運作,則操作根據使用者權限傳回不同的值。有關詳細資訊,請參見listDatabases Behavior行為。

4.Collection Help

a.要檢視目前資料庫中的集合清單,請使用show collections指令:

show collections
           
MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

b.要檢視集合對象上可用方法的幫助(例如db.<collection>),請使用db.<collection>.help()方法:

db.collection.help()
           

<collection>可以是一個存在的集合的名稱,盡管您可以指定一個不存在的集合。

MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

c.要檢視集合方法的實作,請鍵入db.<collection>.<method> name without the圓括号(()),如下面的例子所示,它将傳回save()方法的實作:

db.collection.save
           
MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

提示:如何插入的是數組清單,在代碼中是批量插入。

5.Cursor Help

當您使用mongo shell中的find()方法執行讀操作時,您可以使用各種遊标方法來修改find()行為,并使用各種JavaScript方法來處理find()方法傳回的遊标。

a.要列出可用的修飾符和遊标處理方法,請使用db.collection.find().help()指令:

db.collection.find().help()
           

<collection>可以是一個存在的集合的名稱,盡管您可以指定一個不存在的集合。

MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考
MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考
MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

b.要檢視遊标方法的實作,請鍵入db.<collection>.find().<method> name without the圓括号(()),如下面的例子所示,它将傳回toArray()方法的實作:

db.collection.find().toArray
           
MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

處理遊标的一些有用方法如下:

  • 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之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

如果連接配接到實施通路控制的MongoDB執行個體,則可以使用db.auth()方法進行身份驗證。

另外,可以使用connect()方法連接配接到MongoDB執行個體。下面的示例連接配接到在本地主機上運作的MongoDB執行個體,并使用非預設端口27020設定全局db變量:

db = connect("localhost:27020/myDatabase");
           

2.互動式和腳本蒙戈之間的差別

提示:從4.2版開始,mongo shell提供了 

isInteractive()

方法,該方法傳回一個布爾值,訓示mongo shell是在互動模式還是腳本模式下運作。

MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、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中的資料類型

本節将介紹以下内容:

  • Types
    • Date
    • ObjectId
    • NumberLong
    • NumberInt
    • NumberDecimal
  • Check Types in the 

    mongo

     Shell
    • instanceof

    • typeof

MongoDB BSON支援JSON之外的其他資料類型。驅動程式在宿主語言中為這些資料類型提供本地支援,mongo shell還提供了幾個幫助類來支援在mongo JavaScript shell中使用這些資料類型。有關其他資訊,請參閱擴充JSON引用。

1.類型

1.1 日期

mongo shell提供了各種方法來傳回日期,可以是字元串,也可以是日期對象:

  • Date(),該方法将傳回目前日期的字元串。
  • new Date()構造函數,它使用ISODate()包裝器傳回一個日期對象。
  • ISODate()構造函數,使用ISODate()包裝器傳回一個日期對象。
MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

在内部,日期對象存儲為一個有符号的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
           

操作傳回字元串。

MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

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
           
MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

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之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考

提示:要在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 

mongo

 shell without connecting to a database.

To connect later, see Opening New Connections.

--shell

Used in conjunction with a JavaScript file (i.e. <file.js>) to continue in the 

mongo

 shell after running the JavaScript file.

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 

listDatabases

 command. If the deployment runs with access control, the operation returns different values based on user privileges. See listDatabases Behavior for details.

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 collections

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 

listDatabases

 command. If the deployment runs with access control, the operation returns different values based on user privileges. See listDatabases Behavior for details.

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

, as in the following example:

copy

copied

coll = db.myCollection;
      
You can perform operations on the 

myCollection

 using the variable, as in the following example:

copy

copied

coll.find();
      

db.collection.find()

Find all documents in the collection and returns a cursor.

See the 

db.collection.find()

 and Query Documents for more information and examples.

See Iterate a Cursor in the mongo Shell for information on cursor handling in the 

mongo

 shell.

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支援的按鍵:

MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考
MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考
MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、mongo Shell快速參考
MongoDB之mongo shell程式設計一、配置mongo Shell二、通路mongo Shell幫助三、為mongo Shell編寫腳本四、mongo Shell中的資料類型五、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操作選擇集合中的所有文檔。

下面的示例選擇使用者集合中名稱字段等于“Joe”的文檔:

coll = db.users;
coll.find( { name: "Joe" } );
      
有關指定<query>條件的更多資訊,請參見 Specify Equality Condition.

db.collection.find(<query>, <projection>)

查找與<query>條件比對的文檔,并僅傳回<projection>中的特定字段。

下面的示例從集合中選擇所有文檔,但隻傳回name字段和_id字段。除非顯式指定不傳回,否則總是傳回_id。

coll = db.users;
coll.find( { }, { name: true } );
      
For more information on specifying the 

<projection>

, see Project Fields to Return from Query.

db.collection.find().sort(<sort order>)

傳回指定的<排序順序>的結果。

以下示例從集合中選擇所有文檔,并傳回按名稱字段升序排序的結果(1)。降序使用-1:

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()

傳回與查詢比對的文檔總數。

count()忽略limit()和skip()。例如,如果100條記錄比對,但是限制是10,count()将傳回100。這将比您自己疊代更快,但仍然需要時間。

db.collection.findOne(<query>)

查找并傳回單個文檔。如果沒有找到,則傳回null。

下面的示例在使用者集合中選擇一個user字段與“Joe”比對的文檔:

coll = db.users;
coll.findOne( { name: "Joe" } );
      
Internally, the 

findOne()

 method is the 

find()

 method with a 

limit(1)

.

有關更多資訊和示例,請參見 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

參考之前的文檔。