1. 程式人生 > >Linux下的Mongodb部署應用梳理

Linux下的Mongodb部署應用梳理

helper nod asdf direct 字段名 語法 dir 查詢條件 client

一、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/mogodb.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

Linux下的Mongodb部署應用梳理