mongodb學習筆記

mongodb學習筆記

2017年05月20日 22:03:36 張小秋博客 閱讀數 2158更多javascript

分類專欄: 數據庫java

版權聲明:本文爲博主原創文章,遵循 CC 4.0 by-sa 版權協議,轉載請附上原文出處連接和本聲明。linux

本文連接:https://blog.csdn.net/xqzhang8/article/details/72588278web

啓動mongodb

經過mongod啓動mongodb服務正則表達式

  1. mongod參數選項mongodb

    [root@primary bin]# ./mongod –helpshell

    -h [ --help ]         幫助信息
      --version             版本信息
      -f [ --config ] arg   配置文件選項
      -v [ --verbose ]      提升內部報告標準輸出或記錄到logpath配置的日誌文件中
      --port                指定服務端口(默認27017)
      --auth                啓用驗證
      --noauthrun           不啓用驗證
      --nohttpinterface     關閉http接口,默認關閉27018端口訪問
      --fork                以守護進程的方式運行MongoDB,建立服務器進程(後臺運行)
      --bind_ip             綁定服務IP,若綁定127.0.0.1,則只能本機訪問(默認本地全部IP)
      --maxConns            最大同時鏈接數 默認2000
      --logpath             指定MongoDB日誌文件,注意是指定文件不是目錄
      --logappend           使用追加的方式寫日誌
      --pidfilepath         PID File 的完整路徑,若是沒有設置,則沒有PID文件(pidfilepath=/path/mongod.pid )
      --keyFile             集羣的私鑰的完整路徑,只對於Replica Set 架構有效
      --setParameter        設置參數(mongod --setParameter textSearchEnabled=true)
      --nounixsocket        關閉unix socket 監聽
      --unixSocketPrefix    UNIX域套接字替代目錄,(默認爲 /tmp)
      --sysloglog           
      --cpu                 按期顯示CPU的CPU利用率和iowait
      --dbpath              指定數據庫路徑(默認/data/db/)
      --diaglog             選項 0=off 1=W 2=R 3=both 7=W+some reads
      --directoryperdbeach  數據庫將存儲在一個單獨的目錄中
      --ipv6                IPV6(默認關閉)
      --journal             啓用日誌選項,MongoDB的數據操做將會寫入到journal文件夾的文件裏
      --journalCommitInterval buffer刷新到JournalFile的時間間隔
      --journalOptions      啓用日誌診斷選項
      --jsonp               容許JSONP形式經過HTTP訪問(有安全影響) 
      --nojournal           禁用日誌選項
      --noprealloc          不預先分配存儲
      --noscripting         禁用腳本引擎
      --notablescan         不容許表掃描
      --nssize arg (=16)    設置信數據庫.ns文件大小(MB)
      --profile             檔案參數 0=off 1=slow, 2=all
      --quota               將每一個數據庫限制到必定數量的文件(8個默認值)
      --quotaFiles          #argnumber of files allowed per db, requires --quota
      --repair              #修復全部db
      --repairpath          指定修復文件路徑(defaults to dbpath)
      --rest                開啓restful http interface,默認是關閉的(控制restful查詢接口)
      --shutdown            關閉服務器進程{db.shutdownServer();}
      --slowms arg (=100)   #value of slow for profile and console log
      --smallfilesuse a     #smaller default file size
      --syncdelay arg (=60) 數據寫入磁盤的時間秒數(0=never,不推薦)
      --sysinfo             打印一些診斷系統信息
      --upgrade             若是須要升級數據庫
    
    //複製選項:
      --oplogSize arg       設置oplog的大小(MB). default is 5% of disk space 
    
      主/從參數:
      --master              master mode
      --slave               slave mode
      --source              從節點指定主節點的IP和端口 <server:port>
      --only arg            從庫指定單一的數據庫複製
      --slavedelay          設置從庫同步主庫的延遲時間
      --autoresync          若是從庫與主庫同步數據差得多,自動從新同步
    
    
      Replica set(副本集)選項:
      --replSet arg         設置副本集名稱,格式 <setname>[/<optionalseedhostlist>]
      --replIndexPrefetch   默認all,secondary副本集的成員將加載全部索引到內存中或只會加載_id索引[none|_id_only|all]
    
      分片選項:
      --configsvr           聲明這是一個集羣的config服務,默認端口27019,默認目錄/data/configdb
      --shardsvrdeclare     this is a shard db of a cluster; default port 27018
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
  2. mongod啓動服務數據庫

    /mongodb/mongodb/bin/mongod --dbpath=/mongodb/mongodb/bin/db
    /mongodb/mongodb/bin/mongod --dbpath=/mongodb/mongodb/bin/db --rest --port=27017 --fork
    說明:
    默認端口:27017 
    web控制檯端口:27017+1000=28017
    http://localhost:28017
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  3. 參數使用json

    --config  將配置放到config文件。
    建立:
    mkdir -p /mongodb/mongodb/config/
    mkdir -p /mongodb/mongodb/config/db
    cp mongod /mongodb/mongodb/config/
    vi c.config
    port=27018
    dbpath=/mongodb/mongodb/config/db
    啓動
    mongod --config=/mongodb/mongodb/config/c.config
    登陸:
    mongo 127.0.0.1:27018
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

關閉mongodb

> use admin
    switched to db admin

    > db.shutdownServer()
    Sun Sep  4 02:33:44.407 DBClientCursor::init call() failed
    server should be down...
    Sun Sep  4 02:33:44.408 trying reconnect to 127.0.0.1:27017
    Sun Sep  4 02:33:44.408 reconnect 127.0.0.1:27017 failed couldn't connect to server 127.0.0.1:27017
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

client訪問mongodb

  1. mongo參數選項api

    [root@primary bin]# ./mongo --help
    MongoDB shell version: 2.4.9
    usage: ./mongo [options] [db address] [file names (ending in .js)]
    db address can be:
      foo   
      192.169.0.5/foo   
      192.169.0.5:9999/foo
    
    選項:
      --shell                   從命令行運行完一個 .js 文件後,停留在shell中,而不是結束
      --nodb                    不鏈接數據庫方式啓動,稍後可使用 new Mongo() 或 connect() 來創建鏈接
      --quiet                   安靜輸出
      --port                    鏈接端口
      --host                    鏈接主機
      --eval                    #mongo admin --eval "mongo shell指令「
      -u                        認證用戶
      -p                        認證密碼
      --authenticationDatabase  //>mongo --authenticationDatabase admin -u testuser -p 
      --authenticationMechanism //(=MONGODB-CR)
      -h [ --help ]             幫助信息
      --version                 //show version information
      --verbose                 -v詳細模式,多個v能夠增長詳細輸出,如-vvvv
      --ipv6enable              //IPv6 support (disabled by default)
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
  2. 啓動例子

    /mongodb/bin/mongo 127.0.0.1:27017
    [root@primary bin]# /mongodb/bin/mongo 127.0.0.1:27017/zxq -u zxq -p 1234
    MongoDB shell version: 2.4.9
    connecting to: 127.0.0.1:27017/zxq
    > 
    > show collections
    aaa
    ddd
    system.indexes
    system.users
    t1
    zxq
    zxq123
    >
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

用戶認證

開啓安全認證以前,須要有一個管理員用戶(admin數據庫中的用戶爲超級管理員

  1. 進入admin數據庫中,分配用戶

    use admin
    db.help()
    > db.addUser("root","1234")
    {
            "user" : "root",
            "readOnly" : false,
            "pwd" : "fa0450e8c3e5fff6005de2f88559c3d9",
            "_id" : ObjectId("57a4f53cda8f119aa039cf34")
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  2. 進入用戶數據庫,分配用戶

    use zxq
    db.addUser("zxq","1234")
    db.addUser("zxqread","1234",true) //只讀用戶
    
    > db.addUser("zxq","1234")
    {
            "user" : "zxq",
            "readOnly" : false,
            "pwd" : "3e7c9de5121b9c6b4c6c289b9c61c8f3",
            "_id" : ObjectId("57a4f607da8f119aa039cf35")
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  3. 服務端開啓安全檢查

    中止服務,並安全檢查方式啓動服務
    mongod --dbpath=./db --port=27017 --auth
    • 1
    • 2
  4. 客戶端鏈接,此時須要認證

    [root@primary bin]# ./mongo 127.0.0.1:27017/zxq
    MongoDB shell version: 2.4.9
    connecting to: 127.0.0.1:27017/zxq
    > show collectionsshow collections
    Sat Aug  6 04:26:15.274 error: {
    "$err" : "not authorized for query on zxq.system.namespaces",
    "code" : 16550
    } at src/mongo/shell/query.js:128
    > 
    此時認證失敗
    >use zxq
    >
    > db.auth("zxq","1234")
    1
    > db.auth("zxq","1234")
    1
    
    >use admin
    > db.auth("root","1234")
    1
    > show collections
    system.indexes
    system.users
    > 
    認證方式經過,能夠進行其它操做
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
  5. 客戶端鏈接,此時須要認證

    for:mongod dbname -u uname -p password
    
    [root@primary bin]# ./mongo admin -u root -p 1234
    MongoDB shell version: 2.4.9
    connecting to: admin
    
    [root@primary bin]# ./mongo zxq -u zxq -p 1234
    MongoDB shell version: 2.4.9
    connecting to: zxq
    
    
    **//只讀用戶測試//**
    
    [root@primary bin]# ./mongo zxq -u readonly -p 1234
    MongoDB shell version: 2.4.9
    connecting to: zxq
    > db.zxq.insert({"zxq":"zxq"})
    not authorized for insert on zxq.zxq
    >
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

DB操做命令

db.addUser(userDocument)

//添加用戶
    > db.addUser("zxq","1234")
    {
            "user" : "zxq",
            "readOnly" : false,
            "pwd" : "3e7c9de5121b9c6b4c6c289b9c61c8f3",
            "_id" : ObjectId("57a4f607da8f119aa039cf35")
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

db.adminCommand(nameOrDocument)

//切換到admin數據庫並執行方法中的命令。
    > db.adminCommand({shutdown : 1})
    { "ok" : 0, "errmsg" : "unauthorized" }
    >
  • 1
  • 2
  • 3
  • 4

db.auth(username, password) //用戶認證(用戶鏈接)

> db.auth("zxq","1234")
    1
  • 1
  • 2

db.cloneDatabase(fromhost) //從另外一個服務器克隆當前選擇的數據庫

> db.cloneDatabase("localhost:27017")
    { "clonedColls" : [ "test.zxq", "test.zzz" ], "ok" : 1 }
    > 

    > db
    test
    > show collectionsshow collections
    system.indexes
    zxq
    zzz
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

db.copyDatabase(fromdb, todb, fromhost)

db.copyDatabase('zxq','zxq1')  //本機zxq庫copy至zxq1
    > db.copyDatabase('zxq','zxq1','127.0.0.1:27017')  //其它主機zxq庫copy至zxq1
    { "ok" : 1 }

    > show dbsshow dbs
    local   0.078125GB
    test0.203125GB
    zxq10.203125GB

    > use zxq1use zxq1
    switched to db zxq1

    > show collectionsshow collections
    aaa
    ddd
    system.indexes
    system.users
    t1
    zxq
    zxq123
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

db.createCollection(name, { size : …, capped : …, max : … } )

db.createCollection("log",{size:1024})
    db.createCollection("zxq", {capped:true, size:100000, max:100})
        //capped當於能夠指定一個表能夠佔用空間的最大空間或指定一個表最大可容納的記錄數
        //指定zxq這個表最大記錄數爲100,當第101條記錄進來時,最先的記錄會被自動刪除
        //限制它的空間大小爲1M,若是超過1M的大小,則會刪除最先的記錄

    > for(var i=1;i<=101;i++){db.zxq2.insert({name:"a"+i,age:1+i})}
    > db.zxq2.find()
    { "_id" : ObjectId("57a599706c11d61f2a14e10a"), "name" : "a2", "age" : 3 } //age:2記錄被自動刪除
    { "_id" : ObjectId("57a599706c11d61f2a14e10b"), "name" : "a3", "age" : 4 }
    { "_id" : ObjectId("57a599706c11d61f2a14e10c"), "name" : "a4", "age" : 5 }
    { "_id" : ObjectId("57a599706c11d61f2a14e10d"), "name" : "a5", "age" : 6 }
    { "_id" : ObjectId("57a599706c11d61f2a14e10e"), "name" : "a6", "age" : 7 }
    { "_id" : ObjectId("57a599706c11d61f2a14e10f"), "name" : "a7", "age" : 8 }
    { "_id" : ObjectId("57a599706c11d61f2a14e110"), "name" : "a8", "age" : 9 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

db.currentOp()

[root@primary zxq]# ./mongo --port=27018
    MongoDB shell version: 2.4.9
    connecting to: 127.0.0.1:27018/test
    > db.currentOp()  //顯示當前的操做
    {
            "inprog" : [
                    {
                            "opid" : 887864,
                            "active" : true,
                            "secs_running" : 0,
                            "op" : "insert",
                            "ns" : "zxq1.zxq3",
                            "insert" : {

                            },
                            "client" : "127.0.0.1:24327",
                            "desc" : "conn2",
                            "threadId" : "0x7fec8fc71700",
                            "connectionId" : 2,
                            "locks" : {
                                    "^" : "w",
                                    "^zxq1" : "W"
                            },
                            "waitingForLock" : false,
                            "numYields" : 0,
                            "lockStats" : {
                                    "timeLockedMicros" : {

                                    },
                                    "timeAcquiringMicros" : {
                                            "r" : NumberLong(0),
                                            "w" : NumberLong(1)
                                    }
                            }
                    }
            ]
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

db.dropDatabase()

//刪除當前鏈接的數據庫
    > use zxq1use zxq1
    switched to db zxq1
    > db.dropDatabase()db.dropDatabase()
    { "dropped" : "zxq1", "ok" : 1 }
    > show dbsshow dbs
    local   0.078125GB
    test    0.203125GB
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

db.eval(func, args)

利用db.eval函數能夠在MongoDB服務器端執行javascript腳本,這個函數先將給定的
    javascript字符串傳遞給MongoDB服務器,在服務器上執行,而後返回結果.

    > db.eval("function(name){return 'hello,'+name;}",['refactor'])
    hello,refactor
  • 1
  • 2
  • 3
  • 4
  • 5

db.fsyncLock()

db.fsyncUnlock()

複製數據文件方式數據庫:
    直接拷貝數據目錄下的一切文件。可是在拷貝過程當中必須阻止數據文件發生更改。
    所以須要對數據庫加鎖,以防止數據寫入。

    > db.fsyncLock()
        {
                "info" : "now locked against writes, use db.fsyncUnlock() to unlock",
                "seeAlso" : "http://dochub.mongodb.org/core/fsynccommand",
                "ok" : 1
        }
        > 
    上面的命令將阻塞寫入操做,並將髒數據刷新到磁盤上,確保數據一致。
    而後,拷貝數據文件到備份目錄下

    而後,拷貝數據文件到備份目錄下
    cp -R /data/db/* /backup

    文件複製完成後,對數據庫進行解鎖,容許寫操做
    > db.fsyncUnlock()
    > 

    注意: 在執行db.fsyncLock()和db.fsyncUnlock()時,
    不能關閉當前的shell窗口,不然可能沒法鏈接而須要從新啓動mongod服務。

    恢復時,確保mongod沒有運行,清空數據目錄,將備份的數據拷貝到數據目錄下,
    而後啓動mongod
    # cp -R /backup/* /data/db/
    # mongod -f mongod.conf
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

db.getCollection(cname)

//獲取文檔名稱
    > db.getCollection("zxq")
    zxq.zxq

    //文檔重命名
    > db.getCollection('zxq').renameCollection('zxqzxq')
    { "ok" : 1 }
    > show collectionsshow collections
    aaa
    ddd
    system.indexes
    system.users
    t1
    zxq123
    zxqzxq
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

db.getCollectionNames()

> db.getCollectionNames()
    [
            "aaa",
            "ddd",
            "system.indexes",
            "system.users",
            "t1",
            "zxq123",
            "zxqzxq"
    ]

    //等同於show collections
    > show collections
    aaa
    ddd
    system.indexes
    system.users
    t1
    zxq123
    zxqzxq
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

db.getLastError()

db.getLastErrorObj()

//db.getLastError()返回上一次錯誤-若是沒有錯誤則爲空
    //db.getLastErrorObj()查看完整的錯誤結果。
      在沒有錯誤的狀況下,db.getLastErrorObj().err應該爲空。

    > db.getLastError()
    null

    > db.getLastErrorObj()
    { "n" : 0, "connectionId" : 3, "err" : null, "ok" : 1 }

    > db.getLastErrorObj().err
    null
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

db.getMongo()

> db.getMongo()db.getMongo()
    connection to 127.0.0.1
    >
  • 1
  • 2
  • 3

db.getMongo().setSlaveOk()

對於replica set 中的secondary 節點默認是不可讀的。在寫多讀少的應用中,
    使用Replica Sets來實現讀寫分離。經過在鏈接時指定或者在主庫指定slaveOk,
    由Secondary來分擔讀的壓力,Primary只承擔寫操做。
    若是經過shell訪問mongo,要在secondary進行查詢。會出現以下錯誤:
    imageSet:SECONDARY> db.fs.files.find()
    error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

    有兩種方法實現從機的查詢:
    第一種方法:db.getMongo().setSlaveOk();
    第二種方法:rs.slaveOk();
    可是這種方式有一個缺點就是,下次再經過mongo進入實例的時候,查詢仍然會報錯,爲此能夠經過下列方式
    vi ~/.mongorc.js
    增長一行rs.slaveOk();
    這樣的話之後每次經過mongo命令進入均可以查詢了


    //若是是經過java訪問secondary的話則會報下面的異常
    com.mongodb.MongoException: not talking to master and retries used up
    解決的辦法不少:
    第一種方法:在java代碼中調用dbFactory.getDb().slaveOk();

    第二種方法:在java代碼中調用
    dbFactory.getDb().setReadPreference(ReadPreference.secondaryPreferred());
    //在複製集中優先讀secondary,若是secondary訪問不了的時候就從master中讀
    或
    dbFactory.getDb().setReadPreference(ReadPreference.secondary());
    //只從secondary中讀,若是secondary訪問不了的時候就不能進行查詢

    第三種方法:在配置mongo的時候增長slave-ok="true"也支持直接從secondary中讀
    <mongo:mongo id="mongo" host="${mongodb.host}" port="${mongodb.port}">
            <mongo:options slave-ok="true"/> 
    </mongo:mongo>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

db.getName()

> db.getName()
    zxq
    //等同db
    > db
    zxq
  • 1
  • 2
  • 3
  • 4
  • 5

db.getPrevError()

查詢以前的錯誤信息
    > db.getPrevError();
    { "err" : null, "n" : 0, "nPrev" : -1, "ok" : 1 }
    > 
    清除錯誤記錄
    > db.resetError();
    { "ok" : 1 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

db.getProfilingLevel()

mongodb能夠經過profile來監控數據,進行優化
    查看當前是否開啓profile功能用命令
    返回level等級,值爲0|1|2,分別表明意思:
    0表明關閉,1表明記錄慢命令,2表明所有
    開始profile功能:
    db.setProfilingLevel(level);  
    #level等級,值同上
    level爲1的時候,執行較慢命令默認值爲100ms,更改成
    db.setProfilingLevel(level,slowms)
    如db.setProfilingLevel(1,50)這樣就更改成50毫秒

    > db.system.profile.find({millis:{$gt:500}}) //所花時間大於500毫秒
    >  
    { "ts" : ISODate("2011-07-23T02:50:13.941Z"), 
    "info" : "query order.order reslen:11022 nscanned:672230  \nquery: { status: 1.0 } nreturned:101
     bytes:11006 640ms", "millis" : 640 }  
    { "ts" : ISODate("2011-07-23T02:51:00.096Z"), 
    "info" : "query order.order reslen:11146 nscanned:672302  \nquery: { status: 1.0, user.uid: 
    { $gt: 1663199.0 } }  nreturned:101 bytes:11130 647ms", "millis" : 647 }  

    註釋:
    ts:命令執行時間
    info:命令的內容
        query:表明查詢
        order.order: 表明查詢的庫與集合
        reslen:返回的結果集大小,byte數
        nscanned:掃描記錄數量
        nquery:後面是查詢條件
        nreturned:返回記錄數及用時
        millis:所花時間
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

db.setProfilingLevel(level,) 0=off 1=slow 2=all

db.getProfilingStatus()

> db.getProfilingStatus()db.getProfilingStatus()
    { "was" : 0, "slowms" : 100 }

    > db.setProfilingLevel(1,50)
    { "was" : 0, "slowms" : 100, "ok" : 1 }

    > db.getProfilingStatus()
    { "was" : 1, "slowms" : 50 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

db.getReplicationInfo()

獲取當前數據庫集羣的複製集信息。
  • 1

db.getSiblingDB(name)

> db.getSiblingDB("zxq")
    zxq
  • 1
  • 2

db.hostInfo()

> db.hostInfo()
    {
            "system" : {
                    "currentTime" : ISODate("2016-08-06T09:42:13.512Z"),
                    "hostname" : "primary",
                    "cpuAddrSize" : 64,
                    "memSizeMB" : 2910,
                    "numCores" : 1,
                    "cpuArch" : "x86_64",
                    "numaEnabled" : false
            },
            "os" : {
                    "type" : "Linux",
                    "name" : "",
                    "version" : ""
            },
            "extra" : {
                    "versionString" : "Linux version 2.6.32-358.el6.x86_64 
                    (mockbuild@x86-022.build.eng.bos.redhat.com) 
                    (gcc version 4.4.7 20120313 
                    (Red Hat 4.4.7-3) (GCC) ) #1 SMP Tue Jan 29 11:47:41 EST 2013",
                    "libcVersion" : "2.12",
                    "kernelVersion" : "2.6.32-358.el6.x86_64",
                    "cpuFrequencyMHz" : "2497.522",
                    "cpuFeatures" : "fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca 
                    cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx rdtscp lm constant_tsc up 
                    rep_good xtopology nonstop_tsc unfair_spinlock pni pclmulqdq monitor ssse3 cx16 
                    sse4_1 sse4_2 popcnt aes xsave avx rdrand hypervisor lahf_lm",
                    "pageSize" : NumberLong(4096),
                    "numPages" : 745116,
                    "maxOpenFiles" : 1024
            },
            "ok" : 1
    }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

db.isMaster()

//主庫狀態
    > db.isMaster()
    {
            "ismaster" : true,
            "maxBsonObjectSize" : 16777216,
            "maxMessageSizeBytes" : 48000000,
            "localTime" : ISODate("2016-08-06T09:45:54.651Z"),
            "ok" : 1
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

db.killOp(opid)

中止(殺死)在當前庫的當前操做,能夠用來殺掉長查詢

    //診斷1(返回全部與寫有關的操做)
    db.currentOp(
       {
         "waitingForLock" : true,
         $or: [
            { "op" : { "$in" : [ "insert", "update", "remove" ] } },
            { "query.findandmodify": { $exists: true } }
        ]
       }
    )


    //診斷2(返回正在運行的操做)
    db.currentOp(
       {
         "active" : true,
         "numYields" : 0,
         "waitingForLock" : false
       }
    )

    //診斷3(在zxq數據庫上運行時長超過3S的操做)
    db.currentOp(
       {
         "active" : true,
         "secs_running" : { "$gt" : 3 },
         "ns" : /^zxq\./
       }
    )

    //診斷4(返回建立索引的操做)        
    db.currentOp(
        {
          $or: [
            { op: "query", "query.createIndexes": { $exists: true } },
            { op: "insert", ns: /\.system\.indexes\b/ }
          ]
        }
    )


    //db.currentOp(true) //顯示全部會話操做,包括空閒
    > db.currentOp(true)
    {
            "inprog" : [
                    {
                            "opid" : 1526256,
                            "active" : true,
                            "secs_running" : 0,
                            "op" : "insert",
                            "ns" : "zxq.zzzz",
                            "insert" : {

                            },
                            "client" : "127.0.0.1:12599",
                            "desc" : "conn4",
                            "threadId" : "0x7ff3135bd700",
                            "connectionId" : 4,
                            "locks" : {
                                    "^" : "w"
                            },
                            "waitingForLock" : false,
                            "numYields" : 0,
                            "lockStats" : {
                                    "timeLockedMicros" : {
                                            "r" : NumberLong(0),
                                            "w" : NumberLong(57)
                                    },
                                    "timeAcquiringMicros" : {
                                            "r" : NumberLong(0),
                                            "w" : NumberLong(7)
                                    }
                            }
                    }
            ]
    }

    //殺掉操做
    > db.killOp(1526256)
    { "info" : "attempting to kill op" }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83

db.listCommands()

來看當前MongoDB支持的全部命令
    一樣可經過運行命令db.runCommand({"listCommands" :1})來查詢全部命令
  • 1
  • 2

db.loadServerScripts()

加載在system.js集合中的額全部腳本
  • 1

db.logout()

//退出
  • 1

db.printCollectionStats()

//顯示文檔信息
    zzzz
    {
            "ns" : "zxq.zzzz",
            "count" : 8044831,
            "size" : 450510504,
            "avgObjSize" : 55.99999602229059,
            "storageSize" : 582864896,
            "numExtents" : 18,
            "nindexes" : 1,
            "lastExtentSize" : 153874432,
            "paddingFactor" : 1,
            "systemFlags" : 1,
            "userFlags" : 0,
            "totalIndexSize" : 261157792,
            "indexSizes" : {
                    "_id_" : 261157792
            },
            "ok" : 1
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

db.printReplicationInfo()

db.printShardingStatus()

db.printSlaveReplicationInfo()

顯示覆制相關信息
  • 1

db.removeUser(username)

//刪除用戶
    > db.system.users.find()
    { "_id" : ObjectId("57a4f607da8f119aa039cf35"), 
    "user" : "zxq", "readOnly" : false, "pwd" : "3e7c9de5121b9c6b4c6c289b9c61c8f3" }
    { "_id" : ObjectId("57a4f81edb4b33684ccac174"), 
    "user" : "readonly", "readOnly" : true, "pwd" : "853f224e6274e549814cd58e9248293e" }

    > db.removeUser("readonly")
    > db.system.users.find()
    { "_id" : ObjectId("57a4f607da8f119aa039cf35"), 
    "user" : "zxq", "readOnly" : false, "pwd" : "3e7c9de5121b9c6b4c6c289b9c61c8f3" }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

db.repairDatabase()

//dbrepairDatabase,不只能整理碎片還能夠回收磁盤空間
    > db.repairDatabase()
    > db.runCommand({repairDatabase :1})
    > 期間會產生鎖,建議關閉應用後再進行此操做
    > 所須要的磁盤剩餘空間需求很大
    > 最後一點,這命令能不用最好別用
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

db.resetError()

清除錯誤記錄
  • 1

db.runCommand(cmdObj)

> db.runCommand({repairDatabase :1})
  • 1

db.serverStatus()

//服務器信息
    //修改服務器最大鏈接數
    > db.serverStatus().connectionsdb
    { "current" : 1, "available" : 818, "totalCreated" : NumberLong(6) }

    修改系統參數:
    vi /etc/rc.local
    ulimit -n 30000

    vi /etc/profile
    ulimit -n 30000
    [root@primary ~]# ulimit -a
    core file size          (blocks, -c) 0
    data seg size           (kbytes, -d) unlimited
    scheduling priority             (-e) 0
    file size               (blocks, -f) unlimited
    pending signals                 (-i) 22892
    max locked memory       (kbytes, -l) 64
    max memory size         (kbytes, -m) unlimited
    open files                      (-n) 30000    //已經生效
    pipe size            (512 bytes, -p) 8
    POSIX message queues     (bytes, -q) 819200
    real-time priority              (-r) 0
    stack size              (kbytes, -s) 10240
    cpu time               (seconds, -t) unlimited
    max user processes              (-u) 22892
    virtual memory          (kbytes, -v) unlimited
    file locks                      (-x) unlimited
    [root@primary ~]# 
    配置文件
    bpath=/mongodb/db/
    logpath=/mongodb/logs/mongod.log
    port=27017
    logappend=true
    fork = true
    directoryperdb=true
    #auth=true
    maxConns=30000
    或
    [root@primary bin]# ./mongod --dbpath=./db --maxConns=20000
    查看服務器最大鏈接數
    > db.serverStatus().connections;
    { "current" : 2, "available" : 19998, "totalCreated" : NumberLong(3) }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

db.shutdownServer()

//關閉服務
    > use admin
    switched to db admin
    > db.shutdownServer()
    Sat Aug  6 18:53:47.539 DBClientCursor::init call() failed
    server should be down...
    Sat Aug  6 18:53:47.548 trying reconnect to 127.0.0.1:27017
    Sat Aug  6 18:53:47.548 reconnect 127.0.0.1:27017 failed couldn't connect to server 127.0.0.1:27017
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

db.stats()

//顯示當前DB信息
    > db.stats()
    {
            "db" : "test",
            "collections" : 4,
            "objects" : 101,
            "avgObjSize" : 54.53465346534654,
            "dataSize" : 5508,
            "storageSize" : 32768,
            "numExtents" : 5,
            "indexes" : 2,
            "indexSize" : 16352,
            "fileSize" : 201326592,
            "nsSizeMB" : 16,
            "dataFileVersion" : {
                    "major" : 4,
                    "minor" : 5
            },
            "ok" : 1
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

db.version()

//顯示當前版本
    > db.version()
    2.4.9
    >
  • 1
  • 2
  • 3
  • 4

增、刪、改、查

隱式文檔建立(文檔若是存在,則插入鍵值,若是不存在,建立文檔並插入鍵值

> db.zxq.insert({id:1,name:"zxq"})

    //查詢文檔內容
    > db.zxq.find() 
    { "_id" : ObjectId("57c1c2818ee7bef4894d54b0"), "id" : 1, "name" : "zxq" }

    //求文檔條數
    > db.zxq.count()
    1
    > 

    //3.2 新版功能
    db.zxq.insertOne(
       {
          name: "sue",
          age: 19,
          status: "P"
       }
    )

    //插入多條數據
    db.zxq.insertMany(
       [
         { name: "bob", age: 42, status: "A", },
         { name: "ahn", age: 22, status: "A", },
         { name: "xi", age: 34, status: "D", }
       ]
    )
    //例子
    > db.zxq.find()
    > db.zxq.insertMany(
    ...    [
    ...      { name: "bob", age: 42, status: "A", },
    ...      { name: "ahn", age: 22, status: "A", },
    ...      { name: "xi", age: 34, status: "D", }
    ...    ]
    ... )
    {
        "acknowledged" : true,
        "insertedIds" : [
            ObjectId("57c2b637b854b5b8198eebd3"),
            ObjectId("57c2b637b854b5b8198eebd4"),
            ObjectId("57c2b637b854b5b8198eebd5")
        ]
    }
    > db.zxq.find()
    { "_id" : ObjectId("57c2b637b854b5b8198eebd3"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2b637b854b5b8198eebd4"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2b637b854b5b8198eebd5"), "name" : "xi", "age" : 34, "status" : "D" }


    //多個條件查詢
    > db.zxq.find({age:{$in:[42,22,34]}})
    { "_id" : ObjectId("57c2b637b854b5b8198eebd3"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2b637b854b5b8198eebd4"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2b637b854b5b8198eebd5"), "name" : "xi", "age" : 34, "status" : "D" }
    { "_id" : ObjectId("57c2b7eeb854b5b8198eebd6"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2b7eeb854b5b8198eebd7"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2b7eeb854b5b8198eebd8"), "name" : "xi", "age" : 34, "status" : "D" }
    > 

    > db.zxq.find({_id:{$in:[1,2,3]}})
    { "_id" : 1, "highScore" : 800, "lowScore" : 150 }
    { "_id" : 2, "zxq" : 100 }
    { "_id" : 3, "zxq" : 200
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65

查詢記錄

//查詢全部的內容
    > db.users.find( {} )
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7d"), "name" : "xi", "age" : 34, "status" : "D" }
    > db.users.find()
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7d"), "name" : "xi", "age" : 34, "status" : "D" }

    //單項查詢
    > db.users.find({age:42})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }

    //多條件查詢
    > db.users.find({age:{$in:[42,22]}})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

$lt 小於

> db.users.find({age:{$lt:30}})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    >
  • 1
  • 2
  • 3

$or 或條件

> db.users.find({$or:[{name:"bob" },{age:{$lt:30}}]})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    >
  • 1
  • 2
  • 3
  • 4

與條件

> db.users.find({name:"ahn","age" : 22})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }

    > db.users.find({name:"ahn",$or:[{age:{$lt:30}},{status:"A"}]})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

$gt 大於

> db.users.find({age:{$gt:15,$lt:35}})
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7d"), "name" : "xi", "age" : 34, "status" : "D" }
  • 1
  • 2
  • 3

查詢值爲Null或不存在的字段

db.users.insert(
       [
          { "_id" : 900, "name" : null },
          { "_id" : 901 }
       ]
    )

    > db.users.find()
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7d"), "name" : "xi", "age" : 34, "status" : "D" }
    { "_id" : 900, "name" : null }
    { "_id" : 901 }
    > 

    > db.users.find( { name: null } )
    { "_id" : 900, "name" : null }
    { "_id" : 901 }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

類型篩查(包含值是 null 的 name 字段的文檔,亦即條目字段的值是BSON類型中的Null(即 10 ):

> db.users.find( { name : { $type: 10 } } )
    { "_id" : 900, "name" : null }
  • 1
  • 2

存在性篩查

> db.users.find({name:{$exists:false}})
    { "_id" : 901 }
  • 1
  • 2

$where

> db.zxq.find()
    { "_id" : ObjectId("57c2ce75b854b5b8198eebdb"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("57c2d006b854b5b8198eebdd"), "id" : 2, "name" : "b" }
    { "_id" : ObjectId("57c2d006b854b5b8198eebde"), "id" : 3, "name" : "c" }

    > db.zxq.find({$where:function(){return this.id==3 && this.name=="c"}})
    { "_id" : ObjectId("57c2ce75b854b5b8198eebdb"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("57c2d006b854b5b8198eebde"), "id" : 3, "name" : "c" }
    > 

    > db.zxq.find({$where:function(){ var i=1; return (this.id/i)==3 }})
    { "_id" : ObjectId("57c2ce75b854b5b8198eebdb"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("57c2d006b854b5b8198eebde"), "id" : 3, "name" : "c" }


    > db.zxq.find({$where:function(){return (this.id/1)==3 }})
    { "_id" : ObjectId("57c2ce75b854b5b8198eebdb"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("57c2d006b854b5b8198eebde"), "id" : 3, "name" : "c" }


    >  db.zxq.find({$where:function(){return ( this.id>1&& this.id<3);}})
    { "_id" : ObjectId("57c2d006b854b5b8198eebdd"), "id" : 2, "name" : "b" }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

含有ltltlte gtgtgte $eq 
< <= > >= =

> db.zzz.find();
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579eacf9d3b6760862b1b5c5"), "id" : 2, "name" : "b" }
    { "_id" : ObjectId("579ead08d3b6760862b1b5c6"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("579ead24d3b6760862b1b5c7"), "id" : 3, "name" : "c" }

    範圍查找案例:
    db.zzz.find({id:{$gte:1,$lte:2}})

    > db.zzz.find({id:{$gte:1,$lte:2}})
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579eacf9d3b6760862b1b5c5"), "id" : 2, "name" : "b" }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

OR查詢: 
ininnin $or

> var id={"id":{"$in":[1,2]}}
    > db.zzz.find(id)

    $in查詢
    > var id={"id":{"$in":[1,2]}}
    > db.zzz.find(id)
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579eacf9d3b6760862b1b5c5"), "id" : 2, "name" : "b" }

    $nin查詢
    > db.zzz.find({id:{"$nin":[1,2]}})
    { "_id" : ObjectId("579ead08d3b6760862b1b5c6"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("579ead24d3b6760862b1b5c7"), "id" : 3, "name" : "c" }

    $OR查詢
    > var id={"$or":[{"id":1},{"id":2}]}
    > db.zzz.find(id)

    > db.zzz.find({"$or":[{"id":1},{"id":2}]})
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579eacf9d3b6760862b1b5c5"), "id" : 2, "name" : "b" }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

正則表達式:(相似like) 
db.zzz.find({「name」:/a/})

> db.zzz.find()db.zzz.find()
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579eacf9d3b6760862b1b5c5"), "id" : 2, "name" : "b" }
    { "_id" : ObjectId("579ead08d3b6760862b1b5c6"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("579ead24d3b6760862b1b5c7"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("579ebb3ee7e548e1d8ec6e22"), "id" : 4, "name" : "aa" }
    { "_id" : ObjectId("579ebb51e7e548e1d8ec6e23"), "id" : 5, "name" : "abc" }

    > db.zzz.find({"name":/a/})  --帶有a的 
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579ebb3ee7e548e1d8ec6e22"), "id" : 4, "name" : "aa" }
    { "_id" : ObjectId("579ebb51e7e548e1d8ec6e23"), "id" : 5, "name" : "abc" }

    > db.zzz.find({"name":/a$/}) ---以a開頭的
    { "_id" : ObjectId("579ea974a40cd03459b6ac27"), "id" : 1, "name" : "a" }
    { "_id" : ObjectId("579ebb3ee7e548e1d8ec6e22"), "id" : 4, "name" : "aa" }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

查詢數組

> var single={"name":"jack",address:["anhui","shanghai","beijing"]}
    > db.mytest.insert(single)
    > db.mytest.find()

    { "_id" : ObjectId("567632624163f2ea4dd06e96"), "name" : "jack", "address" : [  "anhui",  "shanghai",  "beijing" ] }
  • 1
  • 2
  • 3
  • 4
  • 5

all操做(檢索數組中須要包含多個元素,all操做(檢索數組中須要包含多個元素,all數組中必須同時包含的條件)

> db.mytest.find({"address":{"$all":["anhui","shanghai"]}})

    { "_id" : ObjectId("567632624163f2ea4dd06e96"), "name" : "jack", "address" : [  "anhui",  "shanghai",  "beijing" ] }

    > db.mytest.find({"address":{"$all":["anhui","s"]}})
  • 1
  • 2
  • 3
  • 4
  • 5

size操做(能夠經過size操做(能夠經過size獲取數組的長度,可是$size不能和比較操做符聯合使用)

> db.mytest.find({"address":{"$size":2}})
    > db.mytest.find({"address":{"$size":3}})
    { "_id" : ObjectId("567632624163f2ea4dd06e96"), "name" : "jack", "address" : [  "anhui",  "shanghai",  "beijing" ] }
  • 1
  • 2
  • 3

slice操做(經過slice操做(經過slice返回數組中的部分數據。」$slice」:2表示數組中的前兩個元素)

> db.mytest.find({"name":"jack"},{"address":{"$slice":1}})
    { "_id" : ObjectId("567632624163f2ea4dd06e96"), "name" : "jack", "address" : [  "anhui" ] }

    > db.mytest.find({"name":"jack"},{"address":{"$slice":2}})
    { "_id" : ObjectId("567632624163f2ea4dd06e96"), "name" : "jack", "address" : [  "anhui",  "shanghai" ] }
  • 1
  • 2
  • 3
  • 4
  • 5

更新記錄

$set 用來指定一個鍵並更新鍵值,若鍵不存在並建立。

$unset 用來刪除鍵

inc修改器inc修改器inc能夠對文檔的某個值爲數字型(只能爲知足要求的數字)的鍵進行增減的操做

$push 向文檔的某個數組類型的鍵添加一個數組元素,不過濾重複的數據。添加時鍵存在,要求鍵值類型必須是數組;鍵不存在,則建立數組類型的鍵

$pushAll 指定多個

$addToSet 往一個數組裏插入記錄

$pop 刪除數組內的一個值

$pull 從數組field內刪除一個等於value值

pullAll同pullAll同pull,能夠一次刪除數組內的多個值

$rename 修改鍵值名稱

$mul 乘

$min

$max

$currentDate

> var single=db.zxq.findOne();
    > single
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "zxq" }
    > single.name="zxq3"
    zxq3
    >  db.zxq.update({name:"zxq"},single);
    >  db.zxq.find(); 
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2, "name" : "zxq1" }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "zxq3" }

    //update更新:
    db.zxq.update(parm1,parm2,parm3,parm4)
    parm1:須要更新的條件
    parm2:更新的對象
    parm3:若是沒有符合條件的對象,是否新增一條記錄,1(新增),默認值爲0
    parm4:若是有多個符合條件的記錄,是否所有更新,默認0,若是所有更新取值1 
    語法:
    db.zxq.update({name:"a"},{$set:{age:20}},0,1)  ---更新age鍵值爲20
    db.zxq.update({name:"a"},{$unset:{age:1}},1,1)  ---刪除age鍵
    db.zxq.update({name:"a"},{$inc:{age:1}},0,1)  ---age數據加1
    db.zxq.update({name:"a"},{$inc:{age:-1}},0,1) ---age數據減1

    例如:
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

set   【語法:db.collection.update( { field: value1 }, {set   【語法:db.collection.update( { field: value1 }, {set: { field1: value2 } } );]

> db.zxq.update({name:"a"},{$set:{age:20}},0,1)  //0表示沒有符合條件的不進行增長
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2, "name" : "zxq1" }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "zxq3" }

    > db.zxq.update({name:"a"},{$set:{age:20}},1,1)  //1表示沒有符合條件的進行增長1行
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2, "name" : "zxq1" }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "zxq3" }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

$unset

> db.zxq.update({id:1},{$unset:{name:1}},0,1)
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

$inc

> db.zxq.update({name:"zxqzxq"},{$inc:{id:1}},0,1)   //0表示沒有符合條件的不進行增長
    > 
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }

    > db.zxq.update({name:"zxqzxq"},{$inc:{id:1}},1,1)  //1表示沒有符合條件的進行增長
    > 
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 1, "name" : "zxqzxq" }
    > 

    > db.zxq.update({name:"zxqzxq"},{$inc:{id:1}},1,1)  //有符合條件的id:1進行增長1
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 2, "name" : "zxqzxq" }

    upsert 參數的更新與parm4=1效果同樣,在沒有符合條件的狀況下增長一條記錄

    > db.zxq.find({id:6})
    > db.zxq.update({id:6},{$set:{name:"xxxx"}})
    > db.zxq.find({id:6})
    > db.zxq.update({id:6},{$set:{name:"xxxx"}},{upsert:true})
    > db.zxq.find({id:6})
    { "_id" : ObjectId("57c1cebad7f41e4ad2dad410"), "id" : 6, "name" : "xxxx" }


    > db.zxq.update({name:"zxqzxq"},{$inc:{id:2}},1,1)  //有符合條件的id:2進行增長2
    > 
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 4, "name" : "zxqzxq" }

    > db.zxq.update({name:"zxqzxq"},{$inc:{id:-2}})   //有符合條件的id:-2進行減小2
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 4, "name" : "zxqzxq" }

    同時更新多條記錄
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1 }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 1, "name" : "zxqzxq" }
    //準備更新id:1的全部記錄
    > db.zxq.update({id:1},{$set:{name:"zxq"}})
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "zxq" }  //被更新了,增長了鍵值
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 1, "name" : "zxqzxq" } //未被更新
    //發現只更新了1條記錄

    > db.zxq.update({id:1},{$set:{name:"aaa"}},0,1)  //1表示,若是存在多條,則同時被更新
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "aaa" }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 1, "name" : "aaa" }

    //{multi:true}一樣達到更新多條目的
    > db.zxq.update({id:1},{$set:{name:"xxxx"}},{multi:true})
    > db.zxq.find()
    { "_id" : ObjectId("57c1c4ea8ee7bef4894d54b2"), "id" : 2 }
    { "_id" : ObjectId("57c1c4368ee7bef4894d54b1"), "id" : 1, "name" : "xxxx" }
    { "_id" : ObjectId("57c1c77cd7f41e4ad2dad40d"), "age" : 20, "name" : "a" }
    { "_id" : ObjectId("57c1c843d7f41e4ad2dad40e"), "id" : 3, "name" : "aa" }
    { "_id" : ObjectId("57c1c98ad7f41e4ad2dad40f"), "id" : 1, "name" : "xxxx" }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86

$push

> db.a.find()
    { "_id" : ObjectId("57c1d3f155a4d399ca642249"), "id" : 1, "size" : "a" }
    { "_id" : ObjectId("57c1d3f555a4d399ca64224a"), "id" : 1, "size" : { "a" : 1, "b" : 2 } }
    { "_id" : ObjectId("57c1d2b7be0a1dfd5217d814"), "id" : 1, "name" : "a", "size" : { "c" : [  3 ] } }
    { "_id" : ObjectId("57c1d4c321b1ed73ff5c2968"), "id" : 2, "size" : { "c" : [  3 ] } }
    > 
    > db.a.update({id:2},{$push:{"size.a":1}})
    > db.a.find()
    { "_id" : ObjectId("57c1d3f155a4d399ca642249"), "id" : 1, "size" : "a" }
    { "_id" : ObjectId("57c1d3f555a4d399ca64224a"), "id" : 1, "size" : { "a" : 1, "b" : 2 } }
    { "_id" : ObjectId("57c1d2b7be0a1dfd5217d814"), "id" : 1, "name" : "a", "size" : { "c" : [  3 ] } }
    { "_id" : ObjectId("57c1d4c321b1ed73ff5c2968"), "id" : 2, "size" : { "a" : [  1 ], "c" : [  3 ] } }  //數組類型的鍵添加一個數組元素

    > db.a.find({id:1})
    { "_id" : ObjectId("57c1d3f155a4d399ca642249"), "id" : 1, "size" : "a" }
    { "_id" : ObjectId("57c1d3f555a4d399ca64224a"), "id" : 1, "size" : { "a" : 1, "b" : 2 } }
    { "_id" : ObjectId("57c1d2b7be0a1dfd5217d814"), "id" : 1, "name" : "a", "size" : { "c" : [  3 ] } }  //向數組中增長元素
    > db.a.update({id:1,name:"a"},{$push:{"size.d":4}},1,0)
    > db.a.find({id:1})
    { "_id" : ObjectId("57c1d3f155a4d399ca642249"), "id" : 1, "size" : "a" }
    { "_id" : ObjectId("57c1d3f555a4d399ca64224a"), "id" : 1, "size" : { "a" : 1, "b" : 2 } }
    { "_id" : ObjectId("57c1d2b7be0a1dfd5217d814"), "id" : 1, "name" : "a", "size" : { "c" : [  3 ], "d" : [  4 ] } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

pushAll  【 語法:{pushAll  【 語法:{pushAll: { : [ , , … ] } } 】指定多個值

> db.a.update({id:1,name:"a"},{$pushAll:{"size.e":[5,6,7]}})
    > db.a.find({id:1})
    { "_id" : ObjectId("57c1d3f155a4d399ca642249"), "id" : 1, "size" : "a" }
    { "_id" : ObjectId("57c1d3f555a4d399ca64224a"), "id" : 1, "size" : { "a" : 1, "b" : 2 } }
    { "_id" : ObjectId("57c1d2b7be0a1dfd5217d814"), "id" : 1, "name" : "a", "size" : { "c" : [  3 ], "d" : [  4 ], "e" : [  5,  6,  7 ] } }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

addToSet  語法:{addToSet  語法:{addToSet: { : , … } }

> db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  10,  20 ] }
    > db.a.update({ id:1 },{ $addToSet: {size: [ 30,40] } })
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  10,  20,  [  30,  40 ] ] }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

addToSet和addToSet和each 是往一個數組裏插入每一個記錄,並保證元素惟一

> db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1 }
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [ 1, 2, 1, 2, 1]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  1,  2 ] }



    //測試數組操做
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  [  1,  2,  1,  2,  3,  4,  5,  6,  7 ] ] }
    > db.a.update({id : 1}, {$addToSet : {size : [1, 2, 1, 2, 3,4,5,6,7]}})
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  [  1,  2,  1,  2,  3,  4,  5,  6,  7 ] ] }
    > db.a.update({id : 1}, {$addToSet : {size : [1, 2, 1, 2, 3,4,5,6,7,8]}})
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [    [   1,  2,  1,  2,  3,  4,  5, 6,   7 ],    

    [   1,  2,  1,  2,  3,  4,  5,  6,  7,  8 ] ] }
    > 


    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1 }
    > db.a.update({id : 1}, {$addToSet : {size : [1, 2, 1, 2]}})
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  [  1,  2,  1,  2 ] ] }
    > 
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [ 1, 2, 1, 2, 1]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  [  1,  2,  1,  2 ],  1,  2 ] }
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [ 1, 2, 1, 2, 1]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  [  1,  2,  1,  2 ],  1,  2 ] }
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [ 1, 2, 1, 2, 1,3,4,5]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  [  1,  2,  1,  2 ],  1,  2,  3,  4,  5 ] }
    > 

    //測試數組操做
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [ 1, 2, 3,4]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  1,  2,  3,  4 ] }
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [ 1, 2, 3,4,5,6,7]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  1,  2,  3,  4,  5,  6,  7 ] }
    > db.a.update({id : 1}, {$addToSet : {size : {$each : [8,9,10]}}}, true)
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  1,  2,  3,  4,  5,  6,  7,  8,  9,  10 ] }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

$pop 只能刪除一個值,也就是說只能用1或-1

> db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  1,  2 ] }
    > db.a.update( { id:1} , { $pop : { "size": -1 } } );
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  2 ] }
    > 

    >  db.a.update( { id:1} , { $pop : { "size": -1 } } );  //-1從前面刪除1個值
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  2,  3,  4,  5,  6,  7,  8,  9,  10 ] }
    > db.a.update( { id:1} , { $pop : { "size": 1 } } );    //1從後面刪除1個值
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  2,  3,  4,  5,  6,  7,  8,  9 ] }
    > db.a.update( { id:1} , { $pop : { "size": 2 } } );    //其它值和1或-1效果同樣
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  2,  3,  4,  5,  6,  7,  8 ] }
    > db.a.update( { id:1} , { $pop : { "size": -2 } } );   //其它值和1或-1效果同樣
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  3,  4,  5,  6,  7,  8 ] }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

$pull

> db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  4,  5,  6,  7,  8 ] }
    > db.a.update( { "id" : 1 } , { $pull : { "size":6} } );
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  4,  5,  7,  8 ] }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

$pullAll

> db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  4,  5,  7,  8 ] }
    > db.a.update({id:1},{$pull:{size:[4,8]}});
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  4,  5,  7,  8 ] }
    > db.a.update({id:1},{$pullAll:{size:[4,8]}});
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  5,  7 ] }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

rename   語法:{rename   語法:{rename: { : , : , … } }

> db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size1" : [  5,  7 ] }
    > db.a.update({id:1},{$rename:{"size1":"size"}});
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  5,  7 ] }
    > 

    > db.a.insert({id:2,"name": { "first" : "george", "last" : "washington" }})
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  5,  7 ] }
    { "_id" : ObjectId("57c27c713b5e3ba4c68d0d78"), "id" : 1 }
    { "_id" : ObjectId("57c27c963b5e3ba4c68d0d79"), "id" : 2, "name" : { "first" : "george", "last" : "washington" } }

    > db.a.update({id:2}, {$rename: { "name.first": "name.fname"}})
    > db.a.find()
    { "_id" : ObjectId("57c273813b5e3ba4c68d0d77"), "id" : 1, "size" : [  5,  7 ] }
    { "_id" : ObjectId("57c27c713b5e3ba4c68d0d78"), "id" : 1 }
    { "_id" : ObjectId("57c27c963b5e3ba4c68d0d79"), "id" : 2, "name" : { "fname" : "george", "last" : "washington" } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

$mul

{ _id: 1, item: "ABC", price: 10.99 }

    db.zxq.update(
       { _id: 1 },
       { $mul: { price: 1.25 } }
    )

    { _id: 1, item: "ABC", price: 13.7375 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

$min

> db.zxq.insert({ _id: 1, highScore: 800, lowScore: 200 })
    WriteResult({ "nInserted" : 1 })
    > db.zxq.find()
    { "_id" : 1, "highScore" : 800, "lowScore" : 200 }
    > db.zxq.update( { _id: 1 }, { $min: { lowScore: 150 } } )
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.zxq.find()
    { "_id" : 1, "highScore" : 800, "lowScore" : 150 }
    > db.zxq.update( { _id: 1 }, { $min: { lowScore: 250 } } )
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
    > db.zxq.find()
    { "_id" : 1, "highScore" : 800, "lowScore" : 150 }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

$max

> db.zxq.find()
    { "_id" : 1, "highScore" : 800, "lowScore" : 150 }
    > db.zxq.update( { _id: 1 }, { $max: { highScore: 950 } } )
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.zxq.find()
    { "_id" : 1, "highScore" : 950, "lowScore" : 150 }
    > db.zxq.update( { _id: 1 }, { $max: { highScore: 870 } } )
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
    > db.zxq.find()
    { "_id" : 1, "highScore" : 950, "lowScore" : 150 }


    > db.a.insert({_id: 1,desc: "crafts",dateEntered: ISODate("2013-10-01 05:00:00"),dateExpired: ISODate("2013-10-01 16:38:16.16")})
    WriteResult({ "nInserted" : 1 })
    > db.a.find()
    { "_id" : 1, "desc" : "crafts", "dateEntered" : ISODate("2013-10-01T05:00:00Z"), "dateExpired" : ISODate("2013-10-01T16:38:16.160Z") }

    > db.a.update({ _id: 1 },{ $max: { dateExpired: new Date("2013-09-30") } })
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
    > db.a.find()
    { "_id" : 1, "desc" : "crafts", "dateEntered" : ISODate("2013-10-01T05:00:00Z"), "dateExpired" : ISODate("2013-10-01T16:38:16.160Z") }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

$currentDate

> db.b.insert({ _id: 1, status: "a", lastModified: ISODate("2013-10-02 01:11:18") })
    WriteResult({ "nInserted" : 1 })

    >  db.b.find()
    { "_id" : 1, "status" : "a", "lastModified" : ISODate("2013-10-02T01:11:18Z") }
    > 

    > db.b.update({ _id: 1 }, { $currentDate: { lastModified: true, "cancellation.date": { $type: "timestamp" }  }, 


    $set: { status: "D", "cancellation.reason": "user request"  }})

    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

    > db.b.find()
    { "_id" : 1, "status" : "D", "lastModified" : ISODate("2016-08-28T06:55:58.745Z"), "cancellation" : 

    { "date" : Timestamp(1472367358, 1), "reason" : "user request" } }
    > 

    > db.b.find()
    { "_id" : 2, "lastModified" : ISODate("2016-08-28T08:47:21.837Z") }

    > db.b.update({ _id:1}, { $currentDate: { lastModified: true}},1,1)
    WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 1 })
    > db.b.find()
    { "_id" : 2, "lastModified" : ISODate("2016-08-28T08:47:21.837Z") }
    { "_id" : 1, "lastModified" : ISODate("2016-08-28T08:48:01.274Z") }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

索引,執行計劃

for (var i=0;i<10000;i++){db.ccc.insert({"name":"a"+i,"age":i+1})}

    > db.ccc.count()
    214069
    > db.ccc.find({age:100})
    { "_id" : ObjectId("57c2e2c56da14df0c2b1cc85"), "name" : "a99", "age" : 100 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

建立B-tree索引

> db.ccc.ensureIndex({age:1}) 

    > db.ccc.find({age:100}).explain()

    {
        "cursor" : "BtreeCursor age_1",
        "isMultiKey" : false,
        "n" : 1,
        "nscannedObjects" : 1,
        "nscanned" : 1,
        "nscannedObjectsAllPlans" : 1,
        "nscannedAllPlans" : 1,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
            "age" : [
                [
                    100,
                    100
                ]
            ]
        },
        "server" : "linux:27017"
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

建立符合索引 (1:表明升序, -1:表明降序)

> db.ccc.ensureIndex({age:1,name:1})
      db.ccc.ensureIndex({"age":1,"name":-1})


    > db.ccc.find({name:"a0"})
    { "_id" : ObjectId("57c2e2c56da14df0c2b1cc22"), "name" : "a0", "age" : 1 }
    > db.ccc.find({name:"a0"}).explain()
    {
        "cursor" : "BtreeCursor name_1",
        "isMultiKey" : false,
        "n" : 1,
        "nscannedObjects" : 1,
        "nscanned" : 1,
        "nscannedObjectsAllPlans" : 1,
        "nscannedAllPlans" : 1,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
            "name" : [
                [
                    "a0",
                    "a0"
                ]
            ]
        },
        "server" : "linux:27017"
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

惟一索引

> db.ccc.ensureIndex({"age":1},{"unique":true})
    >
  • 1
  • 2

查看索引

> db.ccc.getIndexes()
    [
        {
            "v" : 1,
            "key" : {
                "_id" : 1
            },
            "ns" : "test.ccc",
            "name" : "_id_"
        },
        {
            "v" : 1,
            "key" : {
                "age" : 1
            },
            "ns" : "test.ccc",
            "name" : "age_1"
        },
        {
            "v" : 1,
            "key" : {
                "name" : 1
            },
            "ns" : "test.ccc",
            "name" : "name_1"
        },
        {
            "v" : 1,
            "key" : {
                "age" : 1,
                "name" : 1
            },
            "ns" : "test.ccc",
            "name" : "age_1_name_1"
        }
    ]
    > 



    > db.system.indexes.find()  //查看全部索引
    { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.zxq", "name" : "_id_" }
    { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.a", "name" : "_id_" }
    { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.users", "name" : "_id_" }
    { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.ccc", "name" : "_id_" }
    { "v" : 1, "key" : { "age" : 1 }, "ns" : "test.ccc", "name" : "age_1" }
    { "v" : 1, "key" : { "name" : 1 }, "ns" : "test.ccc", "name" : "name_1" }
    { "v" : 1, "key" : { "age" : 1, "name" : 1 }, "ns" : "test.ccc", "name" : "age_1_name_1" }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

刪除索引

刪除集合全部索引
    db.ccc.dropIndexes();

    刪除特定索引 (刪除id字段升序的索引)
    db.ccc.dropIndex({"id":1})
    > db.ccc.dropIndex({"age" : 1})
    { "nIndexesWas" : 2, "ok" : 1 }

    查看索引:
    db.ccc.getIndexes()
    db.system.indexes.find()

    重構索引(慎用)
    db.articles.reIndex();
    注意:索引排序規則升序:1,降序-1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

聚合函數

count

> db.zxq.count()
    1000
  • 1
  • 2

distinct

> db.runCommand({"distinct":"zxq","key":"name"})    

            "a997",
            "a998",
            "a999",
            "a1000"
        ],
        "stats" : {
            "n" : 1000,
            "nscanned" : 1000,
            "nscannedObjects" : 1000,
            "timems" : 2,
            "cursor" : "BasicCursor"
        },
        "ok" : 1
    }


    distinct使用

    db.xxx.distinct("age")
    > db.zzz.distinct("id")
    [ 1, 2, 3, 4, 5 ]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

group

select a,b,sum(c) csum from coll where active=1 group by a,b;

    db.coll.group({
        'key':{
            'a':true,
            'b':true
        },
        'cond':{ 'active':1 },
        'reduce': function(obj, prev)
        {
            prev.csum ++
        },
        'initial':{'csum': 0}
    })


    db.zxq.group({
        'key':{
            'id':true,
            'name':true
        },
        'cond':{ 'id':1 },  //cond用於篩選條件
        'reduce': function(obj, prev) //obj用於掃描行,prev用於輸出結果
        {
            prev.csum ++
        },
        'initial':{'csum': 0}   //設定初始值
    })


    //以下案例
    > db.zxq.find({id:1})
    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f6"), "id" : 1, "name" : "a1" }
    { "_id" : ObjectId("57cbc9a0c2993ede6eb62ade"), "id" : 1, "name" : "a1" }
    { "_id" : ObjectId("57cbc9a2c2993ede6eb62ec6"), "id" : 1, "name" : "a1" }
    { "_id" : ObjectId("57cbc9a5c2993ede6eb632ae"), "id" : 1, "name" : "a1" }

    > db.zxq.group({ 'key':{ 'id':true,'name':true },'cond':{'id':1},'initial':{'csum': 0},'reduce': function(obj, prev) { prev.csum ++ } })
    [ { "id" : 1000, "name" : "a1000", "csum" : 4 } ]

    //寫法二,runCommand
    db.runCommand({group:
        {
            ns:"zxq",
            key:{id:true,name:true},
            initial:{num:0},
            $reduce:function(doc,prev){
            prev.num++}
        }
    });


    //添加篩選條件
    db.zxq.group({key:{id:true,name:true},initial:{num:0},$reduce:function(doc,prev){
        prev.num++
    },
    condition:{id:{$gt:990}}
    });


    //寫法二,添加篩選條件
    db.runCommand({group:
        {
            ns:"zxq",
            key:{id:true,name:true},
            initial:{num:0},
            $reduce:function(doc,prev){
            prev.num++},
            condition:{id:{$gt:998}}
        }
    });

    //使用函數返回值分組
    > db.zxq.group({$keyf:function(doc){return {name:doc.name};},initial:{num:0},$reduce:function(doc,prev){ prev.num++ }, condition:{id:{$gt:997}} });
    [
        {
            "name" : "a998",
            "num" : 4
        },
        {
            "name" : "a999",
            "num" : 4
        },
        {
            "name" : "a1000",
            "num" : 4
        }
    ]
    > 


    //寫法二
    db.runCommand({group:
        {
            ns:"zxq",
            $keyf:function(doc){return {name:doc.name};},
            initial:{num:0},
            $reduce:function(doc,prev){
            prev.num++}
        }
    });


    //使用終結器
    db.zxq.group({$keyf:function(doc){return {name:doc.name};},initial:{num:0},$reduce:function(doc,prev){
        prev.num++
    },condition:{id:{$gt:997}},
    finalize: function(doc){ doc.count=doc.num;delete doc.num; }
    });

    [
        {
            "name" : "a998",
            "count" : 4
        },
        {
            "name" : "a999",
            "count" : 4
        },
        {
            "name" : "a1000",
            "count" : 4
        }
    ]
    > 

    //寫法二
    db.runCommand({group:
        {
            ns:"zxq",
            $keyf:function(doc){return {name:doc.name};},
            initial:{num:0},
            $reduce:function(doc,prev){
            prev.num++},condition:{id:{$gt:997}},
            finalize: function(doc){ doc.count=doc.num;delete doc.num; }
        }
    });

    {
        "retval" : [
            {
                "name" : "a998",
                "count" : 4
            },
            {
                "name" : "a999",
                "count" : 4
            },
            {
                "name" : "a1000",
                "count" : 4
            }
        ],
        "count" : 12,
        "keys" : 3,
        "ok" : 1
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157

MapReduce

能完成count、distinct、group的全部功能

db.runCommand(
    {
        mapreduce:'zxq',
        map:function(){emit(this.name.substr(0,3),this);},
        reduce:function(key,vals){return vals[0];},  //注意:vals是一個Object對象而不是數組
        out:'wq'
    });


    {
        "result" : "wq",
        "timeMillis" : 124,
        "counts" : {
            "input" : 4000,
            "emit" : 4000,
            "reduce" : 387,
            "output" : 99
        },
        "ok" : 1
    }


    注意:
    1.mapreduce是根據map函數裏調用的emit函數的第一個參數來進行分組的
    2.僅當根據分組鍵分組後一個鍵匹配多個文檔,纔會將key和文檔集合交由reduce函數處理。

    db.runCommand(
    {
        mapreduce:'zxq',
        map:function(){emit(this.name.substr(0,3),this);},
        reduce:function(key,vals){return 'wq';}, 
        out:'wq'
    }); 
    //查看wq表數據

    > show collections
    a
    ccc
    system.indexes
    users
    wq
    zxq

    > db.wq.find()
    { "_id" : "a1", "value" : "wq" }
    { "_id" : "a10", "value" : "wq" }
    { "_id" : "a11", "value" : "wq" }
    { "_id" : "a12", "value" : "wq" }
    { "_id" : "a13", "value" : "wq" }
    { "_id" : "a14", "value" : "wq" }
    { "_id" : "a15", "value" : "wq" }
    { "_id" : "a16", "value" : "wq" }
    { "_id" : "a17", "value" : "wq" }
    { "_id" : "a18", "value" : "wq" }
    { "_id" : "a19", "value" : "wq" }
    { "_id" : "a2", "value" : "wq" }
    { "_id" : "a20", "value" : "wq" }
    { "_id" : "a21", "value" : "wq" }
    { "_id" : "a22", "value" : "wq" }
    { "_id" : "a23", "value" : "wq" }
    { "_id" : "a24", "value" : "wq" }
    { "_id" : "a25", "value" : "wq" }
    { "_id" : "a26", "value" : "wq" }
    { "_id" : "a27", "value" : "wq" }
    Type "it" for more

    //案例二:group的功能
    > map = function() { for (var key in this) { emit(key, {count : 1}); }};

    > reduce = function(key, emits) { total = 0; for (var i in emits) { total += emits[i].count; } return {"count" : total}; }

    > db.runCommand({"mapreduce" : "zxq", "map" : map, "reduce" : reduce,"out":"result"})
    {
        "result" : "result",
        "timeMillis" : 307,
        "counts" : {
            "input" : 4000,
            "emit" : 12000,
            "reduce" : 120,
            "output" : 3
        },
        "ok" : 1
    }

    //結果集
    > db.result.find()
    { "_id" : "_id", "value" : { "count" : 4000 } }
    { "_id" : "id", "value" : { "count" : 4000 } }
    { "_id" : "name", "value" : { "count" : 4000 } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89

刪除記錄

> db.zxq.remove({id:1})
    > db.zxq.find()

    > db.zxq.deleteOne({id:2})
    { "acknowledged" : true, "deletedCount" : 1 }
    > db.zxq.find({})
    { "_id" : ObjectId("57c2ce75b854b5b8198eebdb"), "id" : 3, "name" : "c" }
    > 

    > db.zxq.deleteMany({"name" : "a"})
    { "acknowledged" : true, "deletedCount" : 1 }
    > db.zxq.find({})
    { "_id" : ObjectId("57c2ce75b854b5b8198eebdb"), "id" : 3, "name" : "c" }
    { "_id" : ObjectId("57c2d006b854b5b8198eebdd"), "id" : 2, "name" : "b" }
    { "_id" : ObjectId("57c2d006b854b5b8198eebde"), "id" : 3, "name" : "c" }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

遊標

建立測試表

> for (i=1;i<=1000;i++){db.zxq.insert({id:i,name:"a"+i})}
  • 1

定義遊標

var cursor = db.zxq.find();
    while (cursor.hasNext()){obj=cursor.next();print(obj.id);}

    //增長函數
    > db.zxq.find().limit(3)   //顯示前面3行
    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f6"), "id" : 1, "name" : "a1" }
    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f7"), "id" : 2, "name" : "a2" }
    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f8"), "id" : 3, "name" : "a3" }

    > db.zxq.find().skip(3).limit(3)  //跳過前面3行,顯示3行
    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f9"), "id" : 4, "name" : "a4" }
    { "_id" : ObjectId("57cbbbe7c2993ede6eb626fa"), "id" : 5, "name" : "a5" }
    { "_id" : ObjectId("57cbbbe7c2993ede6eb626fb"), "id" : 6, "name" : "a6" }

    > db.zxq.find().limit(3).sort({id:-1}) //降序排序
    { "_id" : ObjectId("57cbbbe7c2993ede6eb62add"), "id" : 1000, "name" : "a1000" }
    { "_id" : ObjectId("57cbbbe7c2993ede6eb62adc"), "id" : 999, "name" : "a999" }
    { "_id" : ObjectId("57cbbbe7c2993ede6eb62adb"), "id" : 998, "name" : "a998" }

    > db.zxq.find().limit(3).sort({id:1}) //升序排序
    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f6"), "id" : 1, "name" : "a1" }
    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f7"), "id" : 2, "name" : "a2" }
    { "_id" : ObjectId("57cbbbe7c2993ede6eb626f8"), "id" : 3, "name" : "a3" }

    //分頁處理
    var cursor1 = db.zxq.find().limit(100);
    var cursor2 = db.zxq.find().skip(100).limit(100);
    var cursor3 = db.zxq.find().skip(200).limit(100);
    while (cursor1.hasNext()){obj=cursor1.next();print(obj.id);}
    while (cursor2.hasNext()){obj=cursor2.next();print(obj.id);}
    while (cursor3.hasNext()){obj=cursor3.next();print(obj.id);}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

手動迭代遊標

> var myCursor = db.users.find({status:"A"});
    > myCursor
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"), "name" : "bob", "age" : 42, "status" : "A" }
    { "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"), "name" : "ahn", "age" : 22, "status" : "A" }
    > 

    > var myCursor = db.users.find({status:"A"});
    > myCursor.hasNext()
    true

    > print(tojson(myCursor.next()))
    {
        "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"),
        "name" : "bob",
        "age" : 42,
        "status" : "A"
    }
    > print(tojson(myCursor.next()))
    {
        "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"),
        "name" : "ahn",
        "age" : 22,
        "status" : "A"
    }
    > print(tojson(myCursor.next()))
    Sun Aug 28 04:28:24.382 error hasNext: false at src/mongo/shell/query.js:124
    > 

    //遊標2
    > var myCursor = db.users.find({status:"A"});
    > printjson(myCursor.next())
    {
        "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7b"),
        "name" : "bob",
        "age" : 42,
        "status" : "A"
    }
    > printjson(myCursor.next())
    {
        "_id" : ObjectId("57c2ba213b5e3ba4c68d0d7c"),
        "name" : "ahn",
        "age" : 22,
        "status" : "A"
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

GridFs

數據庫中存放二進制文件超過16M時,使用GridFs,GridFS在數據庫中,默認使用fs.chunks和fs.files來存儲文件。其中fs.files集合存放文件的信息,fs.chunks存放文件數據。

[root@linux bin]# echo "zxq is good" >zxq.txt  //建立文件
    [root@linux bin]# cat zxq.txt 
    zxq is good

    [root@linux bin]# ./mongofiles put zxq.txt    //文件傳輸到數據庫中
    connected to: 127.0.0.1
    added file: { _id: ObjectId('57cc32ac747f6865ca501e58'), filename: "zxq.txt", chunkSize: 262144, uploadDate: new Date(1473000108668), md5: "39c87dd1241d8ab74494d88439b7ad9a", length: 12 }
    done!
    [root@linux bin]# 


    > show collections      //查看數據庫中文檔
    a
    ccc
    fs.chunks
    fs.files
    result
    system.indexes
    users
    wq
    zxq
    > db.fs.files.find()   //查看錶中的文件信息
    { "_id" : ObjectId("57cc32ac747f6865ca501e58"), "filename" : "zxq.txt", "chunkSize" : 262144, "uploadDate" : ISODate("2016-09-04T14:41:48.668Z"), "md5" : "39c87dd1241d8ab74494d88439b7ad9a", "length" : 12 }


    [root@linux bin]# rm zxq.txt    //刪除原始文件
    rm: remove regular file `zxq.txt'? yes
    [root@linux bin]# cat zxq.txt
    cat: zxq.txt: No such file or directory
    [root@linux bin]# 

    [root@linux bin]# ./mongofiles list  //查看數據庫中文件
    connected to: 127.0.0.1
    zxq.txt 12
    [root@linux bin]# 


    [root@linux bin]# ./mongofiles get zxq.txt  //從數據庫中取出文件
    connected to: 127.0.0.1
    done write to: zxq.txt
    [root@linux bin]# ls
    bsondump  mongod       mongofiles   mongoperf     mongosniff  zxq.txt
    db        mongodump    mongoimport  mongorestore  mongostat
    mongo     mongoexport  mongooplog   mongos        mongotop
    [root@linux bin]# cat zxq.txt 
    zxq is good
    [root@linux bin]# 

    //傳入第二個文件
    [root@linux bin]# ./mongofiles put zxq1.txt 
    connected to: 127.0.0.1
    added file: { _id: ObjectId('57cc33e4d3e1c4b92d0e0374'), filename: "zxq1.txt", chunkSize: 262144, uploadDate: new Date(1473000420571), md5: "39c87dd1241d8ab74494d88439b7ad9a", length: 12 }
    done!

    [root@linux bin]# ./mongofiles list
    connected to: 127.0.0.1
    zxq.txt 12
    zxq1.txt    12

    > db.fs.files.find()  //查看數據庫中文件信息
    { "_id" : ObjectId("57cc32ac747f6865ca501e58"), "filename" : "zxq.txt", "chunkSize" : 262144, "uploadDate" : ISODate("2016-09-04T14:41:48.668Z"), "md5" : "39c87dd1241d8ab74494d88439b7ad9a", "length" : 12 }
    { "_id" : ObjectId("57cc33e4d3e1c4b92d0e0374"), "filename" : "zxq1.txt", "chunkSize" : 262144, "uploadDate" : ISODate("2016-09-04T14:47:00.571Z"), "md5" : "39c87dd1241d8ab74494d88439b7ad9a", "length" : 12 }

    //查找帶有zxq的文件
    [root@linux bin]# ./mongofiles search zxq
    connected to: 127.0.0.1
    zxq.txt 12
    zxq1.txt    12
    [root@linux bin]# ./mongofiles search zxq.txt
    connected to: 127.0.0.1
    zxq.txt 12
    [root@linux bin]# 


    Mongofiles參數說明:
    –d 指定數據庫 ,默認是fs,Mongofiles list –d testGridfs
    -u –p 指定用戶名,密碼
    -h  指定主機
    -port 指定主機端口
    -c 指定集合名,默認是fs
    -t 指定文件的MIME類型,默認會忽略
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81

journal工做原理

journal文件在MongoDB中的做用至關於redo日誌文件在oracle中的做用,
它能夠在即便服務器意外宕機的狀況下,將數據庫操做進行重演
在64位的機器上,2.0以上版本默認是開啓了journal的,
可是在32位機器上,或者2.0如下的版本中,默認是不開啓journal

默認狀況下mongodb每100毫秒往journal文件中flush一次數據,
不過這是在數據文件和journal文件處於同一磁盤捲上的狀況,而
若是數據文件和journal文件不在同一磁盤捲上時,默認刷新輸出
時間是30毫秒。不過這個毫秒值是能夠修改的,可修改範圍是2~300,
值越低,刷新輸出頻率越高,數據安全度也就越高,但磁盤性能上的開銷也更高。

   journal文件是以「j._」開頭命名的,且是append only的,若是1
個journal文件滿了1G大小,mongodb就會新建立一個journal文件來
使用,一旦某個journal文件所記載的寫操做都被使用過了,mongodb就
會把這個journal文件刪除。一般在journal文件所在的文件夾下,只會
存在2~3個journal文件,除非你使用mongodb每秒都寫入大量的數據。
而使用 smallfiles 這個運行時選項能夠將journal文件大小減至128M大小。

[root@primary journal]# pwd
/mongodb/bin/db/journal
[root@primary journal]# ls -l
total 3145740
-rw------- 1 root root 1073741824 Aug  6 19:03 j._0
-rw------- 1 root root 1073741824 Aug  4 08:01 prealloc.1
-rw------- 1 root root 1073741824 Aug  4 08:01 prealloc.2

首先要知道在這個原理中,存在着兩個file,兩個view。兩個file是 data file 
和 journal file,兩個view是 shared view 和 private view。
兩個file是對磁盤而言的,而兩個view是對內存而言的,下面以圖解
的方式解釋:
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

啓動服務前

啓動服務後,MongoDB請求操做系統將Data file映射到Shared view,此時操做系統只管
映射這個動做,並不將數據加載到Shared view中,而是由MongoDB在須要時再將數據進行加載到Shared view。
  • 1
  • 2

而後,MongoDB再請求操做系統將Shared view映射到Private view,
以後MongDB對數據的讀寫操做都是直接操做的Private view
  • 1
  • 2

若是發生了寫操做

Private view變髒之後,根據journalCommitInterval的設置,
將在必定時間後將寫操做往Journal file中複製,這個過程稱爲「group commit」:
  • 1
  • 2

Journal file中記錄的是原生的操做(raw operation),這些原生的操做能夠
使MongoDB完成如下操做:
    對文檔的插入/更新(document insertion/updates)
    對索引的修改(index modifications)
    對命名空間文件的修改(changes to the namespace files)
這些原生操做告訴了Journal file數據變化發生在Data file的什麼位置。
至此,MongoDB上發生的寫事件能夠被認爲是安全的了,由於這些寫操做已
經被記錄在了Journal file上,即便服務器掉電了,在下次啓動MongoDB時,
Journal file上的寫操做將會被重演。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

接下來,Journal file中記錄的寫操做會應用在Shared view上:

默認每隔60秒,MongoDB請求操做系統將Shared view刷新輸出到Data file:
  • 1

數據就被寫入到數據文件了。這時MongoDB還會將Journal file
中已輸出到Data file的寫操做刪除掉(因爲MongoDB在將Journal 
file中寫操做放到Shared view時,是經過了一個前指針和一個後
指針來操做的,因此MongoDB知道哪些寫操做是被放到Shared view了的,哪些沒有)。

最後,MongoDB還會例行地如一開始同樣,將Shared view映射
到Private view,以保持一致性(也是防止Private view變得太過於髒了)。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

MongoDB 作內存數據庫使用

[root@primary bin]# mkdir /mongodata
    [root@primary bin]# mount -t tmpfs -o size=2048M tmpfs /mongodata
    [root@primary bin]# df -h
    Filesystem            Size  Used Avail Use% Mounted on
    /dev/mapper/rootvg-rootlv 93G   53G   36G  60% /
    tmpfs                 1.5G   72K  1.5G   1% /dev/shm
    /dev/sda1             194M   34M  151M  18% /boot
    tmpfs                 2.0G     0  2.0G   0% /mongodata

    mongodb參數文件
    dbpath=/mongodata
    //能夠減小開銷
    nojournal = true
    smallFiles = true
    noprealloc = true

    使用
    > show dbs
    local   0.078125GB
    test    (empty)
    > use zxquse zxq
    switched to db zxq
    > db.zxq.insert({name:"a"})> 
    > 
    > db.zxq.find()db.zxq.find()
    { "_id" : ObjectId("57a5c68ea9475fc6e6d4cb77"), "name" : "a" }
    >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

數據導出方式備份

  1. 建立測試表

    for(var i=1;i<1000;i++){db.t1.insert({name:"a"+i,age:i+1})}
    • 1
  2. 導出表數據

    mongoexport -h 192.168.111.111:27017 -d zxq -c t1 -o /mongodb/backup/t1.txt
    connected to: 192.168.111.111:27017
    exported 999 records
    • 1
    • 2
    • 3
  3. 刪除測試數據文檔

    [root@primary bin]# > use zxq
    [root@primary bin]# > db.t1.drop()
    [root@primary bin]# ./mongoimport -h 192.168.111.111:27017 -d zxq -c t1 /mongodb/backup/t1.txt
    connected to: 192.168.111.111:27017
    Thu Aug  4 19:51:02.880 check 9 999
    Thu Aug  4 19:51:02.943 imported 999 objects
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  4. 驗證數據是否恢復

    [root@primary bin]#> db.t1.count()
    [root@primary bin]#> 999
    • 1
    • 2

搭建主從備份

  1. 開啓master服務器

    [administrator@localhost ~]$ ./mongod --dbpath=/mongodb/master/db 
    --master -port 27017 --logpath=/mongodb/master/logs/mongodb.log --fork
       --master  標記本身是master服務器。
       --port    指定本身的端口,默認是27017
       --fork    後臺運行啓動進程
    • 1
    • 2
    • 3
    • 4
    • 5
  2. 開啓slave服務器

    [administrator@localhost ~]$ 
    ./mongod --dbpath=/mongodb/slave/db --slave --source=127.0.0.1:27017 
    --port 27018 --logpath=/mongodb/slave/logs/mongodb.log --fork
       --slave:   標記本身是slave服務器
       --source:  標記我須要同步的服務器是誰? 指定的ip。
       --port:     開啓本身的端口,千萬不能和master重複。
       --fork      後臺運行啓動進程
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

副本集=>雙機熱備

配置參數及啓動主從庫

  1. master上

    配置文件master.conf
    port=27017
    dbpath=/mongodb/master/db
    replSet=zxq/127.0.0.1:27018 (zxq爲副本名稱)
    啓動:
    [root@primary master]# ./mongod --config=/mongodb/master/master.conf --fork
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  2. standby上

    配置文件standby.conf
    port=27018
    dbpath=/mongodb/standby/db
    replSet=zxq/127.0.0.1:27017 (zxq爲副本名稱)
    啓動:
    [root@primary standby]# ./mongod --config=/mongodb/standby/standby.conf 
    
    注:
    //若是有第三臺
    port=27019
    dbpath=/mongodb/standby/db
    replSet=zxq/127.0.0.1:27017,127.0.0.1:27018 (zxq爲副本名稱)
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

配置主從同步

  1. 建立過程

    //鏈接到主admin庫
    [root@primary master]# ./mongo 127.0.0.1:27017/admin
    MongoDB shell version: 2.4.9
    connecting to: 127.0.0.1:27017/admin
    > 
    //運行主從同步配置命令
    db.runCommand({"replSetInitiate":{ "_id":"zxq", "members":
    [ {"_id":1,"host":"127.0.0.1:27017"}, {"_id":2,"host":"127.0.0.1:27018"} ]}})
    
    注:
                     zxq  //副本名稱
        "_id":1和"_id":2  //兩個節點的節點ID,不能衝突
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  2. 啓動過程日誌信息

    主節點日誌
    Thu Aug  4 11:29:11.348 [rsStart] trying to contact 127.0.0.1:27018
    Thu Aug  4 11:29:11.385 [rsStart] replSet I am 127.0.0.1:27017     //提示本節點信息
    Thu Aug  4 11:29:11.385 [rsStart] replSet STARTUP2
    Thu Aug  4 11:29:11.388 [rsMgr] replSet total number of votes is even - add arbiter or give one member an extra vote
    Thu Aug  4 11:29:11.390 [rsHealthPoll] replSet member 127.0.0.1:27018 is up  //提示從節點啓動 
    Thu Aug  4 11:29:12.387 [rsSync] replSet SECONDARY
    //從節點日誌
    Thu Aug  4 11:29:11.408 [rsStart] replSet I am 127.0.0.1:27018
    Thu Aug  4 11:29:11.408 [rsStart] replSet got config version 1 from a remote, saving locally
    Thu Aug  4 11:29:11.408 [rsStart] replSet info saving a newer config version to local.system.replset
    Thu Aug  4 11:29:11.412 [rsStart] replSet saveConfigLocally done
    Thu Aug  4 11:29:11.412 [rsStart] replSet STARTUP2
    Thu Aug  4 11:29:11.413 [rsMgr] replSet total number of votes is even - add arbiter or give one member an extra vote
    Thu Aug  4 11:29:11.467 [rsSync] ******
    Thu Aug  4 11:29:11.467 [rsSync] creating replication oplog of size: 2289MB...
    Thu Aug  4 11:29:11.467 [FileAllocator] allocating new datafile /mongodb/standby/db/local.1, filling with zeroes...
    Thu Aug  4 11:29:11.500 [FileAllocator] done allocating datafile /mongodb/standby/db/local.1, size: 2047MB,  took 0.033 secs 
    //從節點接收到主節點的數據
    Thu Aug  4 11:29:11.501 [FileAllocator] allocating new datafile /mongodb/standby/db/local.2, filling with zeroes...
    Thu Aug  4 11:29:11.531 [FileAllocator] done allocating datafile /mongodb/standby/db/local.2, size: 2047MB,  took
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
  3. 檢查主備節點是否生效

    > rs.status()
    {
    "set" : "zxq",
    "date" : ISODate("2016-08-04T03:31:25Z"),
    "myState" : 1, 
    "members" : [
    {
    "_id" : 1,  //站點ID
    "name" : "127.0.0.1:27017",
    "health" : 1,
    "state" : 1,
    "stateStr" : "PRIMARY",  //主節點
    "uptime" : 415,
    "optime" : Timestamp(1470281344, 1),
    "optimeDate" : ISODate("2016-08-04T03:29:04Z"),
    "self" : true
    },
    {
    "_id" : 2, //站點ID
    "name" : "127.0.0.1:27018",
    "health" : 1,
    "state" : 2,
    "stateStr" : "SECONDARY", //從節點
    "uptime" : 134,
    "optime" : Timestamp(1470281344, 1),
    "optimeDate" : ISODate("2016-08-04T03:29:04Z"),
    "lastHeartbeat" : ISODate("2016-08-04T03:31:25Z"),
    "lastHeartbeatRecv" : ISODate("2016-08-04T03:31:25Z"),
    "pingMs" : 0,
    "syncingTo" : "127.0.0.1:27017"
    }
    ],
    "ok" : 1
    }
    
    //備用節點
    [root@primary standby]# ./mongo 127.0.0.1:27018
    MongoDB shell version: 2.4.9
    connecting to: 127.0.0.1:27018/test
    zxq:SECONDARY> 
    zxq:SECONDARY>  //已是備用節點信息
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
  4. 添加仲裁節點

    建立vote目錄,複製mongod、mongo到目錄,並建立db目錄
    
    //建立仲裁節點的配置問題
    [root@primary vote]# vi vote.conf 
    port=27019
    dbpath=/mongodb/vote/db
    
    //啓動仲裁節點
    [root@primary vote]# ./mongod --config=./vote.conf --fork
    
    //在主節點上執行添加仲裁節點的命令
    rs.addArb("127.0.0.1:27019")  //告訴主從27019是仲裁節點
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  5. 仲裁添加完成後日誌信息

    27019上日誌(仲裁節點)
    Thu Aug  4 11:41:28.291 [conn3] end connection 127.0.0.1:27460 (2 connections now open)
    Thu Aug  4 11:41:28.418 [rsHealthPoll] replSet member 127.0.0.1:27017 is up
    Thu Aug  4 11:41:28.418 [rsHealthPoll] replSet member 127.0.0.1:27017 is now in state PRIMARY
    //27017爲PRIMARY
    Thu Aug  4 11:41:28.422 [rsHealthPoll] replSet member 127.0.0.1:27018 is up
    Thu Aug  4 11:41:28.422 [rsHealthPoll] replSet member 127.0.0.1:27018 is now in state SECONDARY
    //27018爲SECONDARY
    
    主庫上日誌
    Thu Aug  4 11:41:28.270 [rsHealthPoll] replset info 127.0.0.1:27019 thinks that we are down
    Thu Aug  4 11:41:28.270 [rsHealthPoll] replSet member 127.0.0.1:27019 is up
    Thu Aug  4 11:41:28.272 [rsHealthPoll] replSet member 127.0.0.1:27019 is now in state STARTUP2
    Thu Aug  4 11:41:30.273 [rsHealthPoll] replSet member 127.0.0.1:27019 is now in state ARBITER
    //27019已經正常
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
  6. 切換測試(中止主庫)

    //關閉主節點服務器進程
    Thu Aug  4 11:49:05.375 [rsMgr] replSet info electSelf 2
    Thu Aug  4 11:49:05.564 [rsMgr] replSet PRIMARY
    Thu Aug  4 11:49:07.287 [rsHealthPoll] replset info 127.0.0.1:27017 heartbeat failed, retrying
    Thu Aug  4 11:49:09.291 [rsHealthPoll] replset info 127.0.0.1:27017 heartbeat failed, retrying
    
    //從庫變主庫
    zxq:SECONDARY> 
    zxq:PRIMARY> 
    zxq:PRIMARY> 
    
    //從庫變主庫,能夠接管業務
    zxq:SECONDARY> db.zxq.find()
    error: { "$err" : "not master and slaveOk=false", "code" : 13435 }
    zxq:PRIMARY> db.zxq.find()
    db.zxq.find()
    { "_id" : ObjectId("57a2931b90d8e955cf551d2c"), "name" : "a", "age" : "10" }
    { "_id" : ObjectId("57a293fe90d8e955cf551d2d"), "name" : "b", "age" : "11" }
    { "_id" : ObjectId("57a2bd7106e8981bb7d168ea"), "name" : "c", "age" : "12" }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

分片

mongodb採用將集合進行拆分,而後將拆分的數據均攤到幾個片上的一種解決方案

  • mongos就是一個路由服務器,它會根據管理員設置的「片鍵」將數據分攤到本身管理的mongod集羣

  • 數據和片的對應關係以及相應的配置信息保存在」config服務器」上

  • 全部的client請求咱們都是由 mongos去轉向的,自己不存留數據

  • mongod: 一個普通的數據庫實例,若是不分片的話,咱們會直接連上mongod。

    127.0.0.1:27017  做爲 mongos服務器
    127.0.0.1:27018  做爲 config 服務器
    127.0.0.1:28000  做爲一個sharing1服務器
    127.0.0.1:28001  做爲一個sharing2服務器
    • 1
    • 2
    • 3
    • 4

配置基本服務

  • 開啓config服務器

    其實就是一個普通的mongod服務。
    /mongodb/config/mongod --port=27018 --dbpath=/mongodb/config/db
    • 1
    • 2
  • 開啓mongos服務

    /mongodb/master/mongos --port=27017 configdb=127.0.0.1:27018
    • 1
  • 開啓兩個片鍵

    /mongodb/s1/mongod --port=28000 --dbpath=/mongodb/s1/db
    /mongodb/s2/mongod --port=28001 --dbpath=/mongodb/s2/db
    • 1
    • 2

初始化配置

  • 將要做爲「片」的機器放到mongos的config配置中

    登陸到mongos
    /mongodb/bin/mongo 127.0.0.1:27017
    connecting to: 127.0.0.1:27017/test
    
    mongos> use admin
    switched to db admin
    
    mongos> db.runCommand({"addshard":"127.0.0.1:28000","allowLocal":true})
        { "shardAdded" : "shard0000", "ok" : 1 }
    mongos> db.runCommand({"addshard":"127.0.0.1:28001","allowLocal":true})
        { "shardAdded" : "shard0001", "ok" : 1 }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • 準備分片文檔

    必定要在分片以前建立 「片鍵」 的索引

    mongos> use test
    switched to db test
    mongos>db.zxq.insert({"name":"jack","age":1})
    mongos> db.zxq.createIndex({"age":1})
    循環插入數據:
    for(var i=1;i<10000;i++){db.zxq.insert({"name":"jack"+i,"age":i})}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 激活並建立分片

    mongos> use admin
    switched to db admin
    mongos> db.runCommand({"enablesharding":"test"})
    mongos> db.runCommand({"shardcollection":"test.zxq","key":{"age":1}})
    { "collectionsharded" : "test.zxq", "ok" : 1 }
    • 1
    • 2
    • 3
    • 4
    • 5
  • 查看分片

    db.shards.find()
相關文章
相關標籤/搜索