Linux下的Mongodb部署應用梳理

散盡浮華發表於2016-08-09

 

一、Mongodb簡介  官網地址:http://www.mongodb.org/   

MongoDB是一個高效能,開源,無模式的文件型資料庫,是當前NoSql資料庫中比較熱門的一種。MongoDB 是一個介於關聯式資料庫和非關聯式資料庫之間的產品,是非關聯式資料庫當中功能
最豐富,最像關聯式資料庫的。它在許多場景下可用於替代傳統的關係型資料庫或鍵/值儲存方式。它是由C++語言編寫的一個基於分散式檔案儲存的開源資料庫系統,它的目的在於為WEB應
用提供可擴充套件的高效能資料儲存解決方案。MongoDB是一個介於關係型資料庫和非關係型資料庫之間的產品,是非關係型資料庫當中功能最豐富,最像關係型資料庫的。它支援的資料結構
非常鬆散,會將資料儲存為一個文件,資料結構由鍵值對(key=>value)組成,是類似於json的bson格式,欄位值可以包含其它文件、陣列和文件陣列,因此可以儲存比較複雜的資料型別。

二、Mongodb特點

MongoDB特點是高效能、易部署、易使用,儲存資料非常方便,最大的特點在於它支援的查詢語言非常強大,其語法有點類似於物件導向的查詢語言,幾乎可以實現類似關係型資料庫單表
查詢的絕大部分功能,而且還支援對資料建立索引。MongoDB的主要特點總結如下:
1)提供了一個面向集合的文件儲存,易儲存物件型別的資料,操作起來比較簡單和容易的非關係型資料庫
2)使用update()命令可以實現替換完成的文件(資料)或者一些指定的資料欄位。
3)支援動態查詢。
4)支援完全索引,包含內部物件,可以在MongoDB記錄中設定任何屬性的索引來實現更快的排序。
5)支援複製和故障恢復。
6)使用高效的二進位制資料儲存,包括大型物件(如視訊等)。
7)GridFS是MongoDB中的一個內建功能,可以用於存放大量小檔案。
8)自動處理碎片,以支援雲端計算層次的擴充套件性;如果負載的增加(需要更多的儲存空間和更強的處理能力),它可以分佈在計算機網路中的其它節點上,這就是所謂的分片。
9)支援RUBY,PYTHON,JAVA,C++,PHP,C#等多種語言。
10)檔案儲存格式為BSON(一種JSON的擴充套件),MongoDB支援豐富的查詢表示式,查詢指令使用JSON形式的標記,可輕易查詢文件中內嵌的物件和陣列。
11)MongoDB允許在服務端執行指令碼,可以用JavaScript編寫某個函式,直接在服務端執行,也可以吧函式的定義儲存在服務端,下次直接呼叫即可。
12)可通過網路訪問,可以通過本地u或者網路建立資料映象,這使得MongoDB含有更強的擴充套件性。

Mongodb的不足之處

1)在叢集分片中的資料分佈不均勻
2)單機可靠性比較差
3)大資料量持續插入,寫入效能有較大波動
4)不支援事務操作。所以事務要求嚴格的系統(如果銀行系統)肯定不能用它。
5)磁碟空間佔用比較大。空間佔用大的原因如下:
  1-> 空間的預分配:為避免形成過多的硬碟碎片,mongodb 每次空間不足時都會申請生成一大塊的硬碟空 間,而且申請的量從 64M、128M、256M 那樣的指數遞增,直到2G為單個檔案
      的最大體積。隨著資料量 的增加,你可以在其資料目錄裡看到這些整塊生成容量不斷遞增的檔案。 
  2-> 欄位名所佔用的空間:為了保持每個記錄內的結構資訊用於查詢,mongodb 需要把每個欄位的 key-value 都以 BSON 的形式儲存,如果 value 域相對於 key 域並不大,比如
      存放數值型的資料,則資料的 overhead 是最大的。一種減少空間佔用的方法是把欄位名儘量取短一些,這樣佔用 空間就小了,但這就要求在易讀 性與空間佔用上作為權衡了。
  3-> 刪除記錄不釋放空間:這很容易理解,為避免記錄刪除後的資料的大規模挪動,原記錄空間不刪除,只 標記“已刪除”即可,以後還可以重複利用。
  4-> 可以定期執行 db.repairDatabase()來整理記錄,但這個過程會比較緩慢

三、Mongodb功能

1)面向集合的儲存:適合儲存物件及JSON形式的資料。
2)動態查詢:Mongo支援豐富的查詢表示式。查詢指令使用JSON形式的標記,可輕易查詢文件中內嵌的物件及陣列。
3)完整的索引支援:包括文件內嵌物件及陣列。Mongo的查詢優化器會分析查詢表示式,並生成一個高效的查詢計劃。
4)查詢監視:Mongo包含一個監視工具用於分析資料庫操作的效能。
5)複製及自動故障轉移:Mongo資料庫支援伺服器之間的資料複製,支援主-從模式及伺服器之間的相互複製。複製的主要目標是提供冗餘及自動故障轉移。
6)高效的傳統儲存方式:支援二進位制資料及大型物件(如照片或圖片)
7)自動分片以支援雲級別的伸縮性:自動分片功能支援水平的資料庫叢集,可動態新增額外的機器。

四、Mongodb使用場景

適用場景:
網站實時資料處理。它非常適合實時的插入、更新與查詢,並具備網站實時資料儲存所需的複製及高度伸縮性;快取,由於效能很高,它適合作為資訊基礎設施的快取層。在系統重啟之後,
由它搭建的持久化快取層可以避免下層的資料來源過載。高伸縮性的場景。非常適合由數十或數百臺伺服器組成的資料庫,它的路線圖中已經包含對MapReduce引擎的內建支援。

不適用場景:
要求高度事務性的系統。傳統的商業智慧應用。複雜的跨文件(表)級聯查詢。

五、Mongodb安裝使用  官網下載地址:http://www.mongodb.org/downloads

1)安裝mongodb
[root@data-server src]# cd /usr/local/src/
[root@data-server src]# tar -zvxf mongodb-linux-x86_64-rhel62-3.4.4
[root@data-server src]# mv mongodb-linux-x86_64-rhel62-3.4.4 /usr/local/mongodb
[root@data-server src]# cd /usr/local/mongodb           //Mongodb主目錄
[root@data-server mongodb]# ll
總用量 120
drwxr-xr-x. 2 root root  4096 6月   3 14:51 bin
-rw-r--r--. 1 root root 34520 4月  21 06:19 GNU-AGPL-3.0
-rw-r--r--. 1 root root 16726 4月  21 06:19 MPL-2
-rw-r--r--. 1 root root  1359 4月  21 06:19 README
-rw-r--r--. 1 root root 55625 4月  21 06:19 THIRD-PARTY-NOTICES
[root@data-server mongodb]# mkdir /usr/local/mongodb/data        //Mongodb資料目錄,可以存放在一個獨立的大分割槽上
[root@data-server mongodb]# mkdir /usr/local/mongodb/log         //Mongodb日誌目錄
 
2)啟動Mongodb
使用mongod命令建立一個mongodb資料庫連結,埠號設定為10001,資料庫的路徑為/usr/local/mongodb/data,日誌路徑為/usr/local/mongodb/log/mongo.log
mongodb的啟動程式放在後臺執行,下面命令執行後,按ctrl+c
[root@data-server mongodb]# nohup /usr/local/mongodb/bin/mongod --dbpath=/usr/local/mongodb/data/ --logpath=/usr/local/mongodb/log/mongo.log &
 
mongodb預設埠是27017
[root@data-server mongodb]# ps -ef|grep mongodb
root     14858 14518  1 15:01 pts/1    00:00:01 /usr/local/mongodb/bin/mongod --dbpath=/usr/local/mongodb/data/ --logpath=/usr/local/mongodb/log/mongo.log
root     14887 14518  0 15:02 pts/1    00:00:00 grep mongodb
[root@data-server bin]# netstat -tunlp|grep 14858
tcp        0      0 0.0.0.0:27017               0.0.0.0:*                   LISTEN      14858/mongod 
[root@data-server mongodb]# lsof -i:27017
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
mongod  14858 root    7u  IPv4 145311      0t0  TCP *:27017 (LISTEN)
 
3)設定mongodb的環境變數
[root@data-server ~]# vim /etc/profile
.......
export PATH=$PATH:/usr/local/mongodb/bin/
[root@data-server ~]# source /etc/profile
 
4)為了更方便的啟動和關閉MongoDB,我們可以使用Shell寫指令碼,當然也可以加入到service中
   更好的方式是採用配置檔案,把MongoDB需要的引數寫入配置檔案,然後在指令碼中引用;
[root@data-server ~]# cat /usr/local/mongodb/mongodb.conf
#代表埠號,如果不指定則預設為27017
port=27017
#MongoDB資料檔案目錄
dbpath=/usr/local/mongodb/data
#MongoDB日誌檔案目錄
logpath=/usr/local/mongodb/log/mongo.log
#日誌檔案自動累加
logappend=true
 
編寫啟動指令碼
[root@data-server ~]# vim /etc/init.d/mongodb
#!/bin/bash
#
# mongod        Start up the MongoDB server daemon
#
  
# source function library
. /etc/rc.d/init.d/functions
#定義命令
CMD=/usr/local/mongodb/bin/mongod
#定義配置檔案路徑
INITFILE=/usr/local/mongodb/mongodb.conf
start()
{
    #&表示後臺啟動,也可以使用fork引數
    $CMD -f $INITFILE &
    echo "MongoDB is running background..."
}
  
stop()
{
    pkill mongod
    echo "MongoDB is stopped."
}
  
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    *)
        echo $"Usage: $0 {start|stop}"
esac
[root@data-server ~]# chmod 755 /etc/init.d/mongodb
[root@data-server ~]# /etc/init.d/mongodb status
用法:/etc/init.d/mongodb {start|stop}
[root@data-server ~]# /etc/init.d/mongodb stop
已終止
[root@data-server ~]# lsof -i:27017
[root@data-server ~]# /etc/init.d/mongodb start
MongoDB is running background...
[root@data-server ~]# lsof -i:27017
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
mongod  15138 root    7u  IPv4 147713      0t0  TCP *:27017 (LISTEN)

通過 shell 連線 MongoDB 服務:(在客戶機上連線本機mongodb:mongo 182.48.115.238:27017)
[root@data-server ~]# mongo
MongoDB shell version v3.4.4
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.4
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
  http://docs.mongodb.org/
Questions? Try the support group
  http://groups.google.com/group/mongodb-user
Server has startup warnings: 
2017-06-03T15:17:54.695+0800 I STORAGE  [initandlisten] 
2017-06-03T15:17:54.695+0800 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2017-06-03T15:17:54.695+0800 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2017-06-03T15:17:55.699+0800 I CONTROL  [initandlisten] 
2017-06-03T15:17:55.700+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-06-03T15:17:55.700+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2017-06-03T15:17:55.700+0800 I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2017-06-03T15:17:55.700+0800 I CONTROL  [initandlisten] 
2017-06-03T15:17:55.700+0800 I CONTROL  [initandlisten] 
2017-06-03T15:17:55.700+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2017-06-03T15:17:55.700+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-06-03T15:17:55.700+0800 I CONTROL  [initandlisten] 
2017-06-03T15:17:55.700+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2017-06-03T15:17:55.700+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-06-03T15:17:55.700+0800 I CONTROL  [initandlisten] 
> help
  db.help()                    help on db methods
  db.mycoll.help()             help on collection methods
  sh.help()                    sharding helpers
  rs.help()                    replica set helpers
  help admin                   administrative help
  help connect                 connecting to a db help
  help keys                    key shortcuts
  help misc                    misc things to know
  help mr                      mapreduce

  show dbs                     show database names
  show collections             show collections in current database
  show users                   show users in current database
  show profile                 show most recent system.profile entries with time >= 1ms
  show logs                    show the accessible logger names
  show log [name]              prints out the last segment of log in memory, 'global' is default
  use <db_name>                set current database
  db.foo.find()                list objects in collection foo
  db.foo.find( { a : 1 } )     list objects in foo where a == 1
  it                           result of the last line evaluated; use to further iterate
  DBQuery.shellBatchSize = x   set default number of items to display on shell
  exit                         quit the mongo shell

-------------------------------------------------mongodb非正常關閉導致啟動失敗問題-------------------------------------------------

之前強制關閉了mongodb,後續再次啟動的時候,發現報錯:
[root@i-omxpbsuo ~]# /usr/local/mongodb/bin/mongod --logpath /usr/local/mongodb/log/system.log --logappend --dbpath /data/mongodb --directoryperdb --auth --journal --profile=1 --slowms=5 --fork 
forked process: 4853
all output going to: /usr/local/mongodb/log/system.log

檢視日誌

這是由於上次mongodb非正常關閉導致的。
解決辦法:
1)刪除資料目錄/data/mongodb 下的 mongod.lock 
[root@i-omxpbsuo ~]# rm -rf /data/mongodb/mongod.lock

2)修復mongodb
[root@i-omxpbsuo ~]# /usr/local/mongodb/bin/mongod --logpath --dbpath /data/mongodb --repair 

3)刪除/data/mongodb/journal 下的 j._4 檔案(或者將journal下的檔案清空)
[root@i-omxpbsuo ~]# rm -rf /data/mongodb/journal/*j._4

4)然後再次啟動mongodb就ok了
[root@i-omxpbsuo ~]# /usr/local/mongodb/bin/mongod --logpath --dbpath /data/mongodb --directoryperdb --auth --journal --profile=1 --slowms=5 --fork &

---------------------------------------------------------
正確關閉mongod 的方法:進入mongo shell
> use admin
> db.shutdownServer()

也可以按照文件粗暴的殺掉它,它內部應該有KILL訊號處理程式。
# killall mongod
 
請不要 kill -9 ,會造成檔案資料混亂丟失repair也無力迴天。
---------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------
也可以採用yum的方式安裝mongodb,操作記錄如下:

1)建立repo
[root@data-server ~]# vim /etc/yum.repos.d/mongodb-org-3.2.repo
[mongodb-org-3.2]  
name=MongoDB Repository  
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/  
gpgcheck=0  
enabled=1 

2)安裝MongoDB和相關工具
[root@data-server ~]# yum install -y mongodb-org

3)啟動Mongodb
[root@data-server ~]# service mongod start
Starting mongod:                                           [  OK  ]
[root@data-server ~]# chkconfig mongod on
[root@data-server ~]# lsof -i:27017
COMMAND   PID   USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
mongod  26130 mongod    6u  IPv4 2773161      0t0  TCP localhost:27017 (LISTEN)

日誌檔案:/var/log/mongodb/mongod.log
配置檔案:/etc/mongod.conf 
資料目錄:/var/lib/mongo/

配置檔案解釋:
[root@data-server ~]# cat /etc/mongod.conf 
# mongo.conf     
    
#where to log     
logpath=/var/log/mongo/mongod.log     
    
logappend=true #以追加方式寫入日誌     
    
# fork and run in background     
fork = true    
    
#port = 27017 #埠     
    
dbpath=/var/lib/mongo #資料庫檔案儲存位置     
directoryperdb=true  
# Enables periodic logging of CPU utilization and I/O wait     
#啟用定期記錄CPU利用率和 I/O 等待     
#cpu = true    
    
# Turn on/off security.  Off is currently the default    
# 是否以安全認證方式執行,預設是不認證的非安全方式     
#noauth = true    
#auth = true    
    
# Verbose logging output.     
# 詳細記錄輸出     
#verbose = true    
    
# Inspect all client data for validity on receipt (useful for    
# developing drivers)用於開發驅動程式時的檢查客戶端接收資料的有效性     
#objcheck = true    
    
# Enable db quota management 啟用資料庫配額管理,預設每個db可以有8個檔案,可以用quotaFiles引數設定     
#quota = true    
# 設定oplog記錄等級     
# Set oplogging level where n is     
#   0=off (default)     
#   1=W     
#   2=R     
#   3=both     
#   7=W+some reads     
#oplog = 0    
    
# Diagnostic/debugging option 動態除錯項     
#nocursors = true    
    
# Ignore query hints 忽略查詢提示     
#nohints = true    
# 禁用http介面,預設為localhost:28017    
# Disable the HTTP interface (Defaults to localhost:27018).這個埠號寫的是錯的     
#nohttpinterface = true    
    
# 關閉伺服器端指令碼,這將極大的限制功能     
# Turns off server-side scripting.  This will result in greatly limited     
# functionality     
#noscripting = true    
# 關閉掃描表,任何查詢將會是掃描失敗     
# Turns off table scans.  Any query that would do a table scan fails.     
#notablescan = true    
# 關閉資料檔案預分配     
# Disable data file preallocation.     
#noprealloc = true    
# 為新資料庫指定.ns檔案的大小,單位:MB     
# Specify .ns file size for new databases.     
# nssize = <size>     
    
# Accout token for Mongo monitoring server.     
#mms-token = <token>     
# mongo監控伺服器的名稱     
# Server name for Mongo monitoring server.     
#mms-name = <server-name>     
# mongo監控伺服器的ping 間隔     
# Ping interval for Mongo monitoring server.     
#mms-interval = <seconds>     
    
# Replication Options 複製選項     
    
# in replicated mongo databases, specify here whether this is a slave or master 在複製中,指定當前是從屬關係     
#slave = true    
#source = master.example.com     
# Slave only: specify a single database to replicate     
#only = master.example.com     
# or     
#master = true    
#source = slave.example.com    

 六、Mongodb的日常操作命令

1)登陸和退出..........................................
mongo 命令直接加MongoDB伺服器的IP地址就可以利用 Mongo 的預設埠號(27017)登陸 Mongo,然後便能夠進行簡單的命令列操作。至於退出,直接 exit,然後回車就好了。

如果預設bind繫結的ip是127.0.0.1以及埠是27017,那麼登陸可以直接用下面兩種都可以:
[root@master-node ~]# mongo
[root@master-node ~]# mongo 127.0.0.1:27017

如果是繫結了固定的ip地址,如bing_ip=182.48.115.236,那麼連線mongodb命令是:
[root@master-node ~]# mongo 182.48.115.238:27017

如果是連線某個庫,命令是
[root@master-node ~]# mongo ip:port/庫名 -u使用者名稱 -p密碼

> help
登陸mongodb資料庫後,可以直接執行help命令進行幫助檢視

> show collections
從以上可以看出,登入後 mongo 會自動連上一個名為 test 的資料庫。如果這個資料庫不存 在,那麼 mongo 會自動建立一個名為 test 的資料庫。上面的例子,由於 Mongo 伺服器上沒 有名為 test 的 db,因此,mongo 新建了一個空的名為 test 的 db。其中,沒有任何 collection。

2)database級操作..........................................

2.1 檢視伺服器上的資料庫
> show dbs
admin         0.000GB
local         0.000GB
master_slave  0.000GB
wangshibo     0.000GB

2.2 切換資料庫
切換到wangshibo資料庫(從預設的 test 資料庫)
> use wangshibo;
switched to db wangshibo;
mongo 中,db 代表當前使用的資料庫。這樣,db 就從原來的 test,變為現在的 wangshibo 資料庫,如果沒有這個庫,就會自動建立

2.3 檢視當前資料庫中的所有集合
> show collections
persons
test

2.4 建立資料庫
mongo 中建立資料庫採用的也是 use 命令,如果 use 後面跟的資料庫名不存在,那麼 mongo 將會新建該資料庫。
不過,實際上只執行 use 命令後,mongo 是不會新建該資料庫的,直到 你像該資料庫中插入了資料。
> use huanqiu
switched to db huanqiu
> show dbs
admin         0.000GB
local         0.000GB
master_slave  0.000GB
wangshibo     0.000GB
到這裡並沒有看到剛才新建的 huanqiu 資料庫。

> db.huanqiu.insert({"name":"testdb"})
WriteResult({ "nInserted" : 1 })
該操作會在 huanqiu 資料庫中新建一個 hello 集合,並在其中插入一條記錄。

> show dbs
admin         0.000GB
huanqiu       0.000GB
local         0.000GB
master_slave  0.000GB
wangshibo     0.000GB
這樣,便可以看到 mongo 的確建立了 huanqiu 資料庫,其中有一個 hello 集合。

2.5 刪除資料庫
刪除當前所在庫。比如這裡已經切換到huanqiu庫,那麼就刪除huanku庫
> db.dropDatabase()
{ "dropped" : "huanqiu", "ok" : 1 }

> show dbs
admin         0.000GB
local         0.000GB
master_slave  0.000GB
wangshibo     0.000GB

2.6 檢視當前資料庫
> db
huanqiu

> db.getName();      //這個上面的命令是一樣的
wangshibo

可以看出刪除 huanqiu 資料庫之後,當前的 db 還是指向它,只有當切換資料庫之後,huanqiu 才會徹底消失。
> use wangshibo
switched to db wangshibo
> db
wangshibo
> show dbs
admin         0.000GB
local         0.000GB
master_slave  0.000GB
wangshibo     0.000GB

2.6.1  修復當前資料庫
> db.repairDatabase();
{ "ok" : 1 }

2.6.2  檢視當前資料庫狀態
> db.stats();
{
  "db" : "wangshibo",
  "collections" : 3,
  "views" : 0,
  "objects" : 6,
  "avgObjSize" : 75.5,
  "dataSize" : 453,
  "storageSize" : 73728,
  "numExtents" : 0,
  "indexes" : 4,
  "indexSize" : 53248,
  "ok" : 1
}

2.6.3 當前db版本
> db.version();
3.4.4

2.6.4 檢視當前db的連結機器地址
> db.getMongo();
connection to 182.48.115.238:27017

2.6.5 從指定主機上克隆資料庫
> db.cloneDatabase("182.48.115.236"); 
{
  "clonedColls" : [ ],
  "ok" : 0,
  "errmsg" : "a collection 'wangshibo.wangshibo' already exists",
  "code" : 48,
  "codeName" : "NamespaceExists"
}


2.6.6  從指定的機器上覆制指定資料庫資料到某個資料庫
將本機的master_slave的資料複製到wangshibo資料庫中
> db.copyDatabase("master_slave", "wangshibo", "127.0.0.1");
{ "ok" : 1 }

3)collection 級操作..........................................

3.1 新建 collection
> db.createCollection("Hello")
{ "ok" : 1 }
> show collections
Hello
wangshibo

直接向一個不存在的 collection 中插入資料也能建立一個 collection。
> db.hello2.insert({"name":"lfqy"})
WriteResult({ "nInserted" : 1 })
> show collections
Hello
hello2
wangshibo

3.2 刪除 collection
> db.Hello.drop()
true
返回 true 說明刪除成功,false 說明沒有刪除成功。

> db.Hello.drop()
false
不存在名為 hello 的 collection,因此,刪除失敗。

3.3 重新命名 collection
將 hello2 集合重新命名為 HELLO
> show collections
hello2
wangshibo
> db.hello2.renameCollection("HELLO")
{ "ok" : 1 }
> show collections
HELLO
wangshibo

3.4 檢視當前資料庫中的所有 collection
> show collections
HELLO
wangshibo

3.5 建立索引在 HELLO 集合上,建立對 ID 欄位的索引,1 代表升序。
> db.HELLO.ensureIndex({ID:1})
{
  "createdCollectionAutomatically" : false,
  "numIndexesBefore" : 1,
  "numIndexesAfter" : 2,
  "ok" : 1
}

4)Record 級的操作................................

4.1 插入操作
4.1.1 向 user 集合中插入兩條記錄
> db.user.insert({'name':'GalGadot','gender':'female','age':28,'salary':11000})
WriteResult({ "nInserted" : 1 })
> db.user.insert({'name':'Mikie Hara','gender':'female','age':26,'salary':7000})
WriteResult({ "nInserted" : 1 })

4.1.2 同樣也可以用 save 完成類似的插入操作
> db.user.save({'name':'Wentworth Earl Miller','gender':'male','age':41,'salary':33000})
WriteResult({ "nInserted" : 1 })

4.2 查詢操作
4.2.1 查詢集合中的所有記錄
> db.user.find()
{ "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
{ "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }

4.2.2 查詢集合中的符合條件的記錄
(1)單一條件
查詢 age 為26 的資料
> db.user.find({"age":26})
{ "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }

查詢 salary 大於 7000 的資料
> db.user.find({salary:{$gt:7000}})
{ "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }

查詢 name 中包含'ent'的資料
> db.user.find({name:/ent/})
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }

查詢 name 以 G 打頭的資料
> db.user.find({name:/^G/})
{ "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }

查詢 name 以 t 結尾的資料
> db.user.find({name:/t$/})
{ "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }

(2)多條件"與"
查詢 age 小於 30,salary 大於 7000 的資料
> db.user.find({age:{$lt:30},salary:{$gt:7000}})
{ "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }

(3)多條件"或"
查詢 age 小於 30,或者 salary 大於 10000 的記錄
> db.user.find({$or:[{salary:{$gt:10000}},{age:{$lt:30}}]})
{ "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
{ "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }

4.2.3 查詢第一條記錄
將上面的 find 替換為 findOne()可以查詢符合條件的第一條記錄。
> db.user.findOne({$or:[{salary:{$gt:10000}},{age:{$lt:25}}]})
{
  "_id" : ObjectId("59328c8aa7865327915046ae"),
  "name" : "GalGadot",
  "gender" : "female",
  "age" : 28,
  "salary" : 11000
}

4.2.4 查詢記錄的指定欄位
查詢 user 集合中所有記錄的 name,age,salary,sex_orientation 欄位
> db.user.find({},{name:1,age:1,salary:1,sex_orientation:true})
{ "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "age" : 28, "salary" : 11000 }
{ "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "age" : 26, "salary" : 7000 }
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "age" : 41, "salary" : 33000 }

注意:這裡的 1 表示顯示此列的意思,也可以用 true 表示。
> db.user.find({},{name:1,age:1,salary:true,sex_orientation:1})
{ "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "age" : 28, "salary" : 11000 }
{ "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "age" : 26, "salary" : 7000 }
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "age" : 41, "salary" : 33000 }

4.2.5 查詢指定欄位的資料,並去重。
查詢 gender 欄位的資料,並去掉重複資料
> db.user.distinct('gender')
[ "female", "male" ]

4.2.6 對查詢結果集的操作
(1)Pretty Print
為了方便,mongo 也提供了 pretty print 工具,db.collection.pretty()或者是 db.collection.forEach(printjson)
> db.user.find().pretty()
{
  "_id" : ObjectId("59328c8aa7865327915046ae"),
  "name" : "GalGadot",
  "gender" : "female",
  "age" : 28,
  "salary" : 11000
}
{
  "_id" : ObjectId("59328c9da7865327915046af"),
  "name" : "Mikie Hara",
  "gender" : "female",
  "age" : 26,
  "salary" : 7000
}
{
  "_id" : ObjectId("59328cd6a7865327915046b0"),
  "name" : "Wentworth Earl Miller",
  "gender" : "male",
  "age" : 41,
  "salary" : 33000
}

(2)指定結果集顯示的條目
a)顯示結果集中的前 3 條記錄
> db.user.find().limit(3)
{ "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
{ "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }

b)查詢第 1 條以後的所有資料
> db.user.find().skip(1)
{ "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }

查詢跳過前2條以後的所有資料
> db.user.find().skip(2)
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
> 

c)對結果集排序
升序
> db.user.find().sort({salary:1})
{ "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
{ "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }

降序
> db.user.find().sort({salary:-1})
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
{ "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
{ "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }

4.2.7 統計查詢結果中記錄的條數
(1)統計集合中的所有記錄條數
> db.user.find().count()
3

(2)查詢符合條件的記錄數
查詢 salary 小於 4000 或大於 10000 的記錄數
> db.user.find({$or: [{salary: {$lt:4000}}, {salary: {$gt:10000}}]}).count()
2

4.3 刪除操作
4.3.1 刪除整個集合中的所有資料

> db.wangshibo.find()
{ "_id" : ObjectId("5932683b156e298477cdf3ad"), "name" : "菜鳥教程" }
> db.wangshibo.remove({})
WriteResult({ "nRemoved" : 1 })
> db.wangshibo.find()
> 
可見 wangshibo中的記錄全部被刪除。

mongo在刪除資料的時候不支援 all * 全部刪除選擇{}就可以全部刪除了
刪除mongodb集合中的資料可以使用remove()函式。remove()函式可以接受一個查詢文件作為可選引數來有選擇性的刪除符合條件的文件。
remove()函式不會刪除集合本身,同時,原有的索引也同樣不會被刪除。
刪除文件是永久性的,不能撤銷,也不能恢復的。因此,在執行remove()函式前先用find()命令來檢視下是否正確,是個比較好的習慣啦。

注意 db.collection.remove()和 drop()的區別,remove()只是刪除了集合中所有的記錄, 而集合中原有的索引等資訊還在,而 
drop()則把集合相關資訊整個刪除(包括索引)。

4.3.2 刪除集合中符合條件的所有記錄
> db.user.find()
{ "_id" : ObjectId("59328c8aa7865327915046ae"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
{ "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
> db.user.remove({name:'GalGadot'})
WriteResult({ "nRemoved" : 1 })
> db.user.find()
{ "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }

4.3.3 刪除集合中符合條件的一條記錄
> db.user.find()
{ "_id" : ObjectId("59328c9da7865327915046af"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
> db.user.remove({salary :{$lt:30000}},1)
WriteResult({ "nRemoved" : 1 })
> db.user.find()
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
> 

當然,也可以是命令:db.user.remove({salary :{$lt:30000}},true),因為true和1是一個意思

4.4 更新操作
4.4.1 賦值更新
db.collection.update(criteria, objNew, upsert, multi )
criteria:update 的查詢條件,類似 sql update 查詢內 where 後面的
objNew:update 的物件和一些更新的操作符(如$,$inc...)等,也可以理解為 sql update 查詢內 set 後面的。
upsert : 如果不存在 update 的記錄,是否插入 objNew,true 為插入,預設是 false,不插 入。
multi : mongodb 預設是 false,只更新找到的第一條記錄,如果這個引數為 true,就把按條 件查出來多條記錄全部更新。

> db.user.find()
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
{ "_id" : ObjectId("593293e2a7865327915046b2"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
{ "_id" : ObjectId("593293f0a7865327915046b3"), "name" : "Gasdfdst", "gender" : "female", "age" : 58, "salary" : 60000 }
{ "_id" : ObjectId("59329401a7865327915046b4"), "name" : "huihui", "gender" : "female", "age" : 18, "salary" : 23100 }
> db.user.update({name:'huihui'},{$set:{age:23}},false,true)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.user.find()
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
{ "_id" : ObjectId("593293e2a7865327915046b2"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
{ "_id" : ObjectId("593293f0a7865327915046b3"), "name" : "Gasdfdst", "gender" : "female", "age" : 58, "salary" : 60000 }
{ "_id" : ObjectId("59329401a7865327915046b4"), "name" : "huihui", "gender" : "female", "age" : 23, "salary" : 23100 }

> db.user.update({name:'lfqy1'},{$set:{age:23}},true,true)
WriteResult({
  "nMatched" : 0,
  "nUpserted" : 1,
  "nModified" : 0,
  "_id" : ObjectId("5932946c9758703fe04b0f73")
})
> db.user.find()
{ "_id" : ObjectId("59328cd6a7865327915046b0"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
{ "_id" : ObjectId("593293e2a7865327915046b2"), "name" : "GalGadot", "gender" : "female", "age" : 28, "salary" : 11000 }
{ "_id" : ObjectId("593293f0a7865327915046b3"), "name" : "Gasdfdst", "gender" : "female", "age" : 58, "salary" : 60000 }
{ "_id" : ObjectId("59329401a7865327915046b4"), "name" : "huihui", "gender" : "female", "age" : 23, "salary" : 23100 }
{ "_id" : ObjectId("5932946c9758703fe04b0f73"), "name" : "lfqy1", "age" : 23 }


4.4.2 增值更新
> db.user.find()
{ "_id" : ObjectId("52453cfb25e437dfea8fd4f4"), "name" : "Gal Gadot", "gender" : "female", "age" : 28, "salary" : 11000 }
{ "_id" : ObjectId("52453d8525e437dfea8fd4f5"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 }
{ "_id" : ObjectId("52453e2125e437dfea8fd4f6"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
{ "_id" : ObjectId("52454155d8947fb70d000000"), "name" : "not known", "sex_orientation" : "male", "age" : 13, "salary" : 30000 }
{ "_id" : ObjectId("5245610881c83a5bf26fc285"), "age" : 23, "name" : "lfqy1" }
{ "_id" : ObjectId("52455f8925e437dfea8fd4fd"), "age" : 23, "gender" : "male", "interest" : "NBA", "name" : "lfqy", "salary" : 1 }
{ "_id" : ObjectId("5245607525e437dfea8fd4fe"), "age" : 23, "gender" : "male", "interest" : "NBA", "name" : "lfqy", "salary" : 2 }

> db.user.update({gender:'female'},{$inc:{salary:50}},false,true)

> db.user.find()
{ "_id" : ObjectId("52453cfb25e437dfea8fd4f4"), "name" : "Gal Gadot", "gender" : "female", "age" : 28, "salary" : 11050 }
{ "_id" : ObjectId("52453d8525e437dfea8fd4f5"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7050 }
{ "_id" : ObjectId("52453e2125e437dfea8fd4f6"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 }
{ "_id" : ObjectId("52454155d8947fb70d000000"), "name" : "not known", "sex_orientation" : "male", "age" : 13, "salary" : 30000 }
{ "_id" : ObjectId("5245610881c83a5bf26fc285"), "age" : 23, "name" : "lfqy1" }
{ "_id" : ObjectId("52455f8925e437dfea8fd4fd"), "age" : 23, "gender" : "male", "interest" : "NBA", "name" : "lfqy", "salary" : 1 }
{ "_id" : ObjectId("5245607525e437dfea8fd4fe"), "age" : 23, "gender" : "male", "interest" : "NBA", "name" : "lfqy", "salary" : 2 }
關於更新操作(db.collection.update(criteria, objNew, upsert, multi )),要說明的 是,如果 upsert 為 true,那麼在沒有找到符合更新條件的情況下,mongo 會在集合中插入 一條記錄其值滿足更新條件的記錄(其中的欄位只有更新條件中涉及的欄位,欄位的值滿足 更新條件),然後將其更新(注意,如果更新條件是$lt 這種不等式條件,那麼 upsert 插入

--------------------------------------------------------------------------------------
其它命令操作:
1、建立一個聚集集合(table)
db.createCollection(“collName”, {size: 20, capped: 5, max: 100});//建立成功會顯示{“ok”:1}
//判斷集合是否為定容量db.collName.isCapped();

2、得到指定名稱的聚集集合(table)
db.getCollection("account");

3、得到當前db的所有聚集集合
db.getCollectionNames();

4、顯示當前db所有聚集索引的狀態
db.printCollectionStats();

三、使用者相關 
1、新增一個使用者
db.addUser("name");
db.addUser("userName", "pwd123", true); 新增使用者、設定密碼、是否只讀

2、資料庫認證、安全模式
db.auth("userName", "123123");

3、顯示當前所有使用者
show users;

4、刪除使用者
db.removeUser("userName");

四、聚集集合查詢 
1、查詢所有記錄
db.userInfo.find();
相當於:select* from userInfo;
預設每頁顯示20條記錄,當顯示不下的情況下,可以用it迭代命令查詢下一頁資料。注意:鍵入it命令不能帶“;”
但是你可以設定每頁顯示資料的大小,用DBQuery.shellBatchSize= 50;這樣每頁就顯示50條記錄了。

2、查詢去掉後的當前聚集集合中的某列的重複資料
db.userInfo.distinct("name");
會過濾掉name中的相同資料
相當於:select distict name from userInfo;

3、查詢age = 22的記錄
db.userInfo.find({"age": 22});
相當於: select * from userInfo where age = 22;

4、查詢age > 22的記錄
db.userInfo.find({age: {$gt: 22}});
相當於:select * from userInfo where age >22;

5、查詢age < 22的記錄
db.userInfo.find({age: {$lt: 22}});
相當於:select * from userInfo where age <22;

6、查詢age >= 25的記錄
db.userInfo.find({age: {$gte: 25}});
相當於:select * from userInfo where age >= 25;

7、查詢age <= 25的記錄
db.userInfo.find({age: {$lte: 25}});

8、查詢age >= 23 並且 age <= 26
db.userInfo.find({age: {$gte: 23, $lte: 26}});

9、查詢name中包含 mongo的資料
db.userInfo.find({name: /mongo/});
//相當於%%
[code]select * from userInfo where name like ‘%mongo%';

10、查詢name中以mongo開頭的
db.userInfo.find({name: /^mongo/});
select * from userInfo where name like ‘mongo%';

11、查詢指定列name、age資料
db.userInfo.find({}, {name: 1, age: 1});
相當於:select name, age from userInfo;
當然name也可以用true或false,當用ture的情況下河name:1效果一樣,如果用false就是排除name,顯示name以外的列資訊。

12、查詢指定列name、age資料, age > 25
db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
相當於:select name, age from userInfo where age >25;

13、按照年齡排序
升序:db.userInfo.find().sort({age: 1});
降序:db.userInfo.find().sort({age: -1});

14、查詢name = zhangsan, age = 22的資料
db.userInfo.find({name: 'zhangsan', age: 22});
相當於:select * from userInfo where name = ‘zhangsan' and age = ‘22';

15、查詢前5條資料
db.userInfo.find().limit(5);
相當於:selecttop 5 * from userInfo;

16、查詢10條以後的資料
db.userInfo.find().skip(10);
相當於:select * from userInfo where id not in (
selecttop 10 * from userInfo
);

17、查詢在5-10之間的資料
db.userInfo.find().limit(10).skip(5);

可用於分頁,limit是pageSize,skip是第幾頁*pageSize

18、or與 查詢
db.userInfo.find({$or: [{age: 22}, {age: 25}]});
相當於:select * from userInfo where age = 22 or age = 25;

19、查詢第一條資料
db.userInfo.findOne();
相當於:selecttop 1 * from userInfo;
db.userInfo.find().limit(1);

20、查詢某個結果集的記錄條數
db.userInfo.find({age: {$gte: 25}}).count();
相當於:select count(*) from userInfo where age >= 20;

21、按照某列進行排序
db.userInfo.find({sex: {$exists: true}}).count();
相當於:select count(sex) from userInfo;

五、索引
1、建立索引
db.userInfo.ensureIndex({name: 1});
db.userInfo.ensureIndex({name: 1, ts: -1});

2、查詢當前聚集集合所有索引
db.userInfo.getIndexes();

3、檢視總索引記錄大小
db.userInfo.totalIndexSize();

4、讀取當前集合的所有index資訊
db.users.reIndex();

5、刪除指定索引
db.users.dropIndex("name_1");

6、刪除所有索引索引
db.users.dropIndexes();

六、修改、新增、刪除集合資料
1、新增
db.users.save({name: ‘zhangsan', age: 25, sex: true});
新增的資料的資料列,沒有固定,根據新增的資料為準

2、修改
db.users.update({age: 25}, {$set: {name: 'changeName'}}, false, true);
相當於:update users set name = ‘changeName' where age = 25;
db.users.update({name: 'Lisi'}, {$inc: {age: 50}}, false, true);
相當於:update users set age = age + 50 where name = ‘Lisi';
db.users.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'hoho'}}, false, true);
相當於:update users set age = age + 50, name = ‘hoho' where name = ‘Lisi';

3、刪除
db.users.remove({age: 132});

4、查詢修改刪除
db.users.findAndModify({
    query: {age: {$gte: 25}}, 
    sort: {age: -1}, 
    update: {$set: {name: 'a2'}, $inc: {age: 2}},
    remove: true
});
db.runCommand({ findandmodify : "users", 
    query: {age: {$gte: 25}}, 
    sort: {age: -1}, 
    update: {$set: {name: 'a2'}, $inc: {age: 2}},
    remove: true
});

update 或 remove 其中一個是必須的引數; 其他引數可選。
引數    詳解     預設值 
query    查詢過濾條件    {} 
sort    如果多個文件符合查詢過濾條件,將以該引數指定的排列方式選擇出排在首位的物件,該物件將被操作    {} 
remove    若為true,被選中物件將在返回前被刪除    N/A 
update    一個 修改器物件
N/A 
new    若為true,將返回修改後的物件而不是原始物件。在刪除操作中,該引數被忽略。    false 
fields    參見Retrieving a Subset of Fields (1.5.0+) 
All fields 
upsert    建立新物件若查詢結果為空。 示例 (1.5.4+) 
false 


七、語句塊操作 
1、簡單Hello World
print("Hello World!");
這種寫法呼叫了print函式,和直接寫入"Hello World!"的效果是一樣的;

2、將一個物件轉換成json
tojson(new Object());
tojson(new Object('a'));

3、迴圈新增資料
> for (var i = 0; i < 30; i++) {
... db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
... };

這樣就迴圈新增了30條資料,同樣也可以省略括號的寫法
> for (var i = 0; i < 30; i++) db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});

也是可以的,當你用db.users.find()查詢的時候,顯示多條資料而無法一頁顯示的情況下,可以用it檢視下一頁的資訊;

4、find 遊標查詢
> var cursor = db.users.find();
> while (cursor.hasNext()) { 
    printjson(cursor.next()); 
}
這樣就查詢所有的users資訊,同樣可以這樣寫
var cursor = db.users.find();
while (cursor.hasNext()) { printjson(cursor.next); }
同樣可以省略{}號

5、forEach迭代迴圈
db.users.find().forEach(printjson);
forEach中必須傳遞一個函式來處理每條迭代的資料資訊

6、將find遊標當陣列處理
var cursor = db.users.find();
cursor[4];
取得下標索引為4的那條資料
既然可以當做陣列處理,那麼就可以獲得它的長度:cursor.length();或者cursor.count();
那樣我們也可以用迴圈顯示資料

for (var i = 0, len = c.length(); i < len; i++) printjson(c[i]);

7、將find遊標轉換成陣列
> var arr = db.users.find().toArray();
> printjson(arr[2]);

用toArray方法將其轉換為陣列

8、定製我們自己的查詢結果
只顯示age <= 28的並且只顯示age這列資料
db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);
db.users.find({age: {$lte: 28}}, {age: true}).forEach(printjson);

排除age的列
db.users.find({age: {$lte: 28}}, {age: false}).forEach(printjson);

9、forEach傳遞函式顯示資訊
db.things.find({x:4}).forEach(function(x) {print(tojson(x));});

八、其他 
1、查詢之前的錯誤資訊
db.getPrevError();

2、清除錯誤記錄
db.resetError();

檢視聚集集合基本資訊
1、檢視幫助  db.yourColl.help();
2、查詢當前集合的資料條數  db.yourColl.count();
3、檢視資料空間大小 db.userInfo.dataSize();
4、得到當前聚集集合所在的db db.userInfo.getDB();
5、得到當前聚集的狀態 db.userInfo.stats();
6、得到聚集集合總大小 db.userInfo.totalSize();
7、聚集集合儲存空間大小 db.userInfo.storageSize();
8、Shard版本資訊  db.userInfo.getShardVersion()
9、聚集集合重新命名 db.userInfo.renameCollection("users"); 將userInfo重新命名為users
10、刪除當前聚集集合 db.userInfo.drop();

show dbs:顯示資料庫列表 
show collections:顯示當前資料庫中的集合(類似關聯式資料庫中的表) 
show users:顯示使用者 
use <db name>:切換當前資料庫,這和MS-SQL裡面的意思一樣 
db.help():顯示資料庫操作命令,裡面有很多的命令 
db.foo.help():顯示集合操作命令,同樣有很多的命令,foo指的是當前資料庫下,一個叫foo的集合,並非真正意義上的命令 
db.foo.find():對於當前資料庫中的foo集合進行資料查詢(由於沒有條件,會列出所有資料) 
db.foo.find( { a : 1 } ):對於當前資料庫中的foo集合進行查詢,條件是資料中有一個屬性叫a,且a的值為1

學習網站:http://www.runoob.com/mongodb/mongodb-tutorial.html

相關文章