1. 程式人生 > >每篇半小時1天入門MongoDB——2.MongoDB環境變量配置和Shell操作

每篇半小時1天入門MongoDB——2.MongoDB環境變量配置和Shell操作

.get same 修復 nss its keys 電腦 sts lis

上一篇:每篇半小時1天入門MongoDB——1.MongoDB介紹和安裝

配置環境變量

Win10系統為例

右鍵單擊“此電腦”——屬性——高級系統設置——高級——環境變量,添加C:\Program Files\MongoDB\Server\3.0\bin;。註意:要以;隔開各種變量。

技術分享

這樣的話就可以直接在CMD命令窗口中輸入mongo

技術分享

表示環境變量設置成功,並已經連接到默認數據庫test中。

我們可以輸入mongod --help來查看相關的幫助信息

技術分享
C:\Users\zouqi>mongod --help
Options:

General options:
  -h [ --help ]               show this usage information
  --version                   show version information
  -f [ --config ] arg         configuration file specifying additional options
  -v [ --verbose ] [=arg(=v)] be more verbose (include multiple times for more
                              verbosity e.g. -vvvvv)
  --quiet                     quieter output
  --port arg                  specify port number - 
27017 by default --bind_ip arg comma separated list of ip addresses to listen on - all local ips by default --ipv6 enable IPv6 support (disabled by default) --maxConns arg max number of simultaneous connections -
1000000 by default --logpath arg log file to send write to instead of stdout - has to be a file, not directory --logappend append to logpath instead of over-writing --logRotate arg set the log rotation behavior (rename|reopen) --timeStampFormat arg Desired format for timestamps in log messages. One of ctime, iso8601-utc or iso8601-local --pidfilepath arg full path to pidfile (if not set, no pidfile is created) --keyFile arg private key for cluster authentication --setParameter arg Set a configurable parameter --httpinterface enable http interface --clusterAuthMode arg Authentication mode used for cluster authentication. Alternatives are (keyFile|sendKeyFile|sendX509|x509) --auth run with security --noauth run without security --jsonp allow JSONP access via http (has security implications) --rest turn on simple rest api --slowms arg (=100) value of slow for profile and console log --profile arg 0=off 1=slow, 2=all --cpu periodically show cpu and iowait utilization --sysinfo print some diagnostic system information --noIndexBuildRetry don‘t retry any index builds that were interrupted by shutdown --noscripting disable scripting engine --notablescan do not allow table scans Windows Service Control Manager options: --install install Windows service --remove remove Windows service --reinstall reinstall Windows service (equivalent to --remove followed by --install) --serviceName arg Windows service name --serviceDisplayName arg Windows service display name --serviceDescription arg Windows service description --serviceUser arg account for service execution --servicePassword arg password used to authenticate serviceUser Replication options: --oplogSize arg size to use (in MB) for replication op log. default is 5% of disk space (i.e. large is good) Master/slave options (old; use replica sets instead): --master master mode --slave slave mode --source arg when slave: specify master as <server:port> --only arg when slave: specify a single database to replicate --slavedelay arg specify delay (in seconds) to be used when applying master ops to slave --autoresync automatically resync if slave data is stale Replica set options: --replSet arg arg is <setname>[/<optionalseedhostlist>] --replIndexPrefetch arg specify index prefetching behavior (if secondary) [none|_id_only|all] Sharding options: --configsvr declare this is a config db of a cluster; default port 27019; default dir /data/configdb --shardsvr declare this is a shard db of a cluster; default port SSL options: --sslOnNormalPorts use ssl on configured ports --sslMode arg set the SSL operation mode (disabled|allowSSL|preferSSL|requireSSL ) --sslPEMKeyFile arg PEM file for ssl --sslPEMKeyPassword arg PEM file password --sslClusterFile arg Key file for internal SSL authentication --sslClusterPassword arg Internal authentication key file password --sslCAFile arg Certificate Authority file for SSL --sslCRLFile arg Certificate Revocation List file for SSL --sslDisabledProtocols arg Comma separated list of TLS protocols to disable [TLS1_0,TLS1_1,TLS1_2] --sslWeakCertificateValidation allow client to connect without presenting a certificate --sslAllowConnectionsWithoutCertificates allow client to connect without presenting a certificate --sslAllowInvalidHostnames Allow server certificates to provide non-matching hostnames --sslAllowInvalidCertificates allow connections to servers with invalid certificates --sslFIPSMode activate FIPS 140-2 mode at startup Storage options: --storageEngine arg (=mmapv1) what storage engine to use --dbpath arg directory for datafiles - defaults to \data\db which is C:\data\db\ based on the current working drive --directoryperdb each database will be stored in a separate directory --noprealloc disable data file preallocation - will often hurt performance --nssize arg (=16) .ns file size (in MB) for new databases --quota limits each database to a certain number of files (8 default) --quotaFiles arg number of files allowed per db, implies --quota --smallfiles use a smaller default file size --syncdelay arg (=60) seconds between disk syncs (0=never, but not recommended) --upgrade upgrade db if needed --repair run repair on all dbs --repairpath arg root directory for repair files - defaults to dbpath --journal enable journaling --nojournal disable journaling (journaling is on by default for 64 bit) --journalOptions arg journal diagnostic options --journalCommitInterval arg how often to group/batch commit (ms) WiredTiger options: --wiredTigerCacheSizeGB arg maximum amount of memory to allocate for cache; defaults to 1/2 of physical RAM --wiredTigerStatisticsLogDelaySecs arg (=0) seconds to wait between each write to a statistics file in the dbpath; 0 means do not log statistics --wiredTigerJournalCompressor arg (=snappy) use a compressor for log records [none|snappy|zlib] --wiredTigerDirectoryForIndexes Put indexes and data in different directories --wiredTigerCollectionBlockCompressor arg (=snappy) block compression algorithm for collection data [none|snappy|zlib] --wiredTigerIndexPrefixCompression arg (=1) use prefix compression on row-store leaf pages
View Code

如果你不喜歡看英文可以網上搜中文幫助介紹。

mongoDB和關系型數據庫的對比

技術分享

  1. 關系數據的表的record必須保證擁有每一個field
  2. mongoDBde meiyige documentde key可以不一樣
  3. 關系型數據庫查詢使用SQL
  4. mongoDB查詢使用內置find函數——》基於BSON的特殊查詢工具

Shell操作

  1. 創建一個數據庫——use[databaseName]

    這時數據庫並沒有被正在創建,而是處於mongodb的一個預處理緩存池當中,如果你什麽也不幹就離開的花這個空數據庫就會被刪除。

    技術分享

  2. 查看所有數據庫——show dbs

    > show dbs
    demo        0.078GB
    local       0.078GB
    myDatabase  0.078GB
    >

    這個時候我們看到myTest這個數據庫是還沒有創建的。

  3. 給指定數據庫添加集合並且添加記錄 ——db.[documentName].insert({...})

    > db.persons.insert({name:‘yujie‘})
    WriteResult({ "nInserted" : 1 })
    >

    執行上面語句後才真正創建數據庫。

    > show dbs
    demo        0.078GB
    local       0.078GB
    myDatabase  0.078GB
    myTest      0.078GB
    >
  4. 查看數據庫中的所有文檔——show collections

    > show collections
    persons
    system.indexes
    >

    我們看到多了一個system.indexes文檔,這是系統自動創建的一個索引文檔,當插入記錄的時候,自動創建了一個字段_id,並在這個字段上面創建了索引。我們來查看下索引:

    > db.system.indexes.find()
    { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "myTest.persons" }
    >
  5. 查看指定文檔的數據——db.[documentName].find()&db.[documentName].findOne()

    在這之前,我們再來往persons文檔中插入一條記錄
    > db.persons.insert({name:‘楚留香‘})
    WriteResult({ "nInserted" : 1 })
    >

    查找persons文檔中的所有記錄

    > db.persons.find()
    { "_id" : ObjectId("593959250ab68d9cc7011a93"), "name" : "yujie" }
    { "_id" : ObjectId("59395c350ab68d9cc7011a94"), "name" : "楚留香" }
    >

    查找persons文檔中的第一條記錄

    > db.persons.findOne()
    { "_id" : ObjectId("593959250ab68d9cc7011a93"), "name" : "yujie" }
    >
  6. 更新文檔數據——db.[documentName].update({查詢條件},{更新內容})

    這裏我們用到了一個update方法,我們來看下它的幾個參數分別代表什麽

    參數1:查詢的條件

    參數2:更新的字段

    參數3:如果不存在則插入

    參數4:是否允許修改多條記錄

    更新name為yujie的記錄

    > db.persons.update({name:‘yujie‘},{$set:{name:‘玉傑‘}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

    查看更新後的記錄:

    > db.persons.find()
    { "_id" : ObjectId("593959250ab68d9cc7011a93"), "name" : "玉傑" }
    { "_id" : ObjectId("59395c350ab68d9cc7011a94"), "name" : "楚留香" }
  7. 刪除文檔中的數據——db.[documentName].remove({...})

    插入一條測試記錄

    > db.persons.insert({name:‘test‘})})
    WriteResult({ "nInserted" : 1 })

    插入後:

    > db.persons.find()
    { "_id" : ObjectId("593959250ab68d9cc7011a93"), "name" : "玉傑" }
    { "_id" : ObjectId("59395c350ab68d9cc7011a94"), "name" : "楚留香" }
    { "_id" : ObjectId("593961530ab68d9cc7011a95"), "name" : "test" }
    >

    刪除文檔中的數據

    > db.persons.remove({name:‘test‘})
    WriteResult({ "nRemoved" : 1 })
    >

    刪除後結果:

    > db.persons.find()
    { "_id" : ObjectId("593959250ab68d9cc7011a93"), "name" : "玉傑" }
    { "_id" : ObjectId("59395c350ab68d9cc7011a94"), "name" : "楚留香" }
    >
  8. 刪除數據庫——db.dropDatabase()

    查看所有數據庫

    > show dbs
    demo        0.078GB
    foobar      0.078GB
    local       0.078GB
    myDatabase  0.078GB
    myTest      0.078GB
    >

    假設我要刪除foobar數據庫,先使用use foobar切換到foobar數據庫,然後執行 db.dropDatabase(),執行結果如下:

    > db.dropDatabase()
    { "dropped" : "foobar", "ok" : 1 }
    >

    再次查看所有數據庫:

    > show dbs
    demo        0.078GB
    local       0.078GB
    myDatabase  0.078GB
    myTest      0.078GB
    >
  9. Shell的help

    裏面有所有的shell可以完成的命令幫助,全局的help數據庫相關的db.help(),集合相關的db.[documentName].help()

    db.help()

    技術分享
    > db.help()
    DB methods:
            db.adminCommand(nameOrDocument) - switches to ‘admin‘ db, and runs command [ just calls db.runCommand(...) ]
            db.auth(username, password)
            db.cloneDatabase(fromhost)
            db.commandHelp(name) returns the help for the command
            db.copyDatabase(fromdb, todb, fromhost)
            db.createCollection(name, { size : ..., capped : ..., max : ... } )
            db.createUser(userDocument)
            db.currentOp() displays currently executing operations in the db
            db.dropDatabase()
            db.eval() - deprecated
            db.fsyncLock() flush data to disk and lock server for backups
            db.fsyncUnlock() unlocks server following a db.fsyncLock()
            db.getCollection(cname) same as db[‘cname‘] or db.cname
            db.getCollectionInfos()
            db.getCollectionNames()
            db.getLastError() - just returns the err msg string
            db.getLastErrorObj() - return full status object
            db.getLogComponents()
            db.getMongo() get the server connection object
            db.getMongo().setSlaveOk() allow queries on a replication slave server
            db.getName()
            db.getPrevError()
            db.getProfilingLevel() - deprecated
            db.getProfilingStatus() - returns if profiling is on and slow threshold
            db.getReplicationInfo()
            db.getSiblingDB(name) get the db at the same server as this one
            db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
            db.hostInfo() get details about the server‘s host
            db.isMaster() check replica primary status
            db.killOp(opid) kills the current operation in the db
            db.listCommands() lists all the db commands
            db.loadServerScripts() loads all the scripts in db.system.js
            db.logout()
            db.printCollectionStats()
            db.printReplicationInfo()
            db.printShardingStatus()
            db.printSlaveReplicationInfo()
            db.dropUser(username)
            db.repairDatabase()
            db.resetError()
            db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }
            db.serverStatus()
            db.setLogLevel(level,<component>)
            db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
            db.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the db
            db.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the db
            db.setVerboseShell(flag) display extra information in shell output
            db.shutdownServer()
            db.stats()
            db.version() current version of the server
    >
    View Code

    db.persons.help()

    技術分享
    > db.persons.help()
    DBCollection help
            db.persons.find().help() - show DBCursor help
            db.persons.count()
            db.persons.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
            db.persons.convertToCapped(maxBytes) - calls {convertToCapped:‘persons‘, size:maxBytes}} command
            db.persons.dataSize()
            db.persons.distinct( key ) - e.g. db.persons.distinct( ‘x‘ )
            db.persons.drop() drop the collection
            db.persons.dropIndex(index) - e.g. db.persons.dropIndex( "indexName" ) or db.persons.dropIndex( { "indexKey" : 1 } )
            db.persons.dropIndexes()
            db.persons.ensureIndex(keypattern[,options])
            db.persons.explain().help() - show explain help
            db.persons.reIndex()
            db.persons.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
                                                          e.g. db.persons.find( {x:77} , {name:1, x:1} )
            db.persons.find(...).count()
            db.persons.find(...).limit(n)
            db.persons.find(...).skip(n)
            db.persons.find(...).sort(...)
            db.persons.findOne([query])
            db.persons.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, ‘new‘: false] } )
            db.persons.getDB() get DB object associated with collection
            db.persons.getPlanCache() get query plan cache associated with collection
            db.persons.getIndexes()
            db.persons.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
            db.persons.insert(obj)
            db.persons.mapReduce( mapFunction , reduceFunction , <optional params> )
            db.persons.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor
            db.persons.remove(query)
            db.persons.renameCollection( newName , <dropTarget> ) renames the collection.
            db.persons.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
            db.persons.save(obj)
            db.persons.stats({scale: N, indexDetails: true/false, indexDetailsKey: <index key>, indexDetailsName: <index name>})
            db.persons.storageSize() - includes free space allocated to this collection
            db.persons.totalIndexSize() - size in bytes of all the indexes
            db.persons.totalSize() - storage allocated for all data and indexes
            db.persons.update(query, object[, upsert_bool, multi_bool]) - instead of two flags, you can pass an object with fields: upsert, multi
            db.persons.validate( <full> ) - SLOW
            db.persons.getShardVersion() - only for use with sharding
            db.persons.getShardDistribution() - prints statistics about data distribution in the cluster
            db.persons.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function
            db.persons.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
            db.persons.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection
            db.persons.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection
    >
    View Code
  10. mongoDB的API

    http://api.mongodb.com/js/

  11. 數據庫和集合命名規範

  1. 不能是空字符串
  2. 不得含有‘ ‘(空格)、,、$、/,\、和\O(空字符);
  3. 應全部小寫
  4. 最多64個字節
  5. 數據庫名不能與現有系統保留庫同名,如admin,local,及config

db-text這樣的集合也是合法的,但是不能通過db.[documentName]得到了,要改為db.getCollection("documentName"),因為db-text會被當成是減。

mongoDB的shell內置javascript引擎可以直接執行js代碼

function insert(object){
db.getCollection("db-text").insert(object)
}
insert({age:29})

shell可以用eval

更多命令

db.AddUser(username,password)  添加用戶
db.auth(usrename,password)     設置數據庫連接驗證
db.cloneDataBase(fromhost)     從目標服務器克隆一個數據庫
db.commandHelp(name)           返回幫助命令
db.copyDatabase(fromdb,todb,fromhost)  復制數據庫fromdb---源數據庫名稱,todb---目標數據庫名稱,fromhost---源數據庫服務器地址
db.createCollection(name,{size:3333,capped:333,max:88888})  創建一個數據集,相當於一個表
db.currentOp()                 取消當前庫的當前操作
db.dropDataBase()              刪除當前數據庫
db.eval(func,args)             運行服務器端代碼
db.getCollection(cname)        取得一個數據集合,其他類似的用法:db[‘cname‘]
db.getCollenctionNames()       取得所有數據集合的名稱列表
db.getLastError()              返回最後一個錯誤的提示消息
db.getLastErrorObj()           返回最後一個錯誤的對象
db.getMongo()                  取得當前服務器的連接對象
db.getMongo().setSlaveOk()     允許當前連接讀取備庫中的成員對象
db.getName()                   返回當操作數據庫的名稱
db.getPrevError()              返回上一個錯誤對象
db.getProfilingLevel()         
db.getReplicationInfo()        獲得重復的數據
db.getSisterDB(name)           獲取服務器上面的數據庫
db.killOp()                    停止(殺死)在當前庫的當前操作
db.printCollectionStats()      返回當前庫的數據集狀態
db.printReplicationInfo()
db.printSlaveReplicationInfo()
db.printShardingStatus()       返回當前數據庫是否為共享數據庫
db.removeUser(username)        刪除用戶
db.repairDatabase()            修復當前數據庫
db.resetError()                
db.runCommand(cmdObj)          運行數據庫命令. 如果cmdObj 是 string類型, 將它轉換為 {cmdObj:1}格式的對象
db.setProfilingLevel(level)    0=off,1=slow,2=all
db.shutdownServer()            關閉當前服務程序
db.version()                   返回當前程序的版本信息
 
db.test.find({id:10})          返回test數據集ID=10的數據集
db.test.find({id:10}).count()  返回test數據集ID=10的數據總數
db.test.find({id:10}).limit(2) 返回test數據集ID=10的數據集從第二條開始的數據集
db.test.find({id:10}).skip(8)  返回test數據集ID=10的數據集從0到第八條的數據集
db.test.find({id:10}).limit(2).skip(8)  返回test數據集ID=1=的數據集從第二條到第八條的數據
db.test.find({id:10}).sort()   返回test數據集ID=10的排序數據集
db.test.findOne([query])       返回符合條件的一條數據
db.test.getDB()                返回此數據集所屬的數據庫名稱
db.test.getIndexes()           返回些數據集的索引信息
db.test.group({key:...,initial:...,reduce:...[,cond:...]})
db.test.mapReduce(mayFunction,reduceFunction,<optional params>)
db.test.remove(query)                      在數據集中刪除一條數據
db.test.renameCollection(newName)          重命名些數據集名稱
db.test.save(obj)                          往數據集中插入一條數據
db.test.stats()                            返回此數據集的狀態
db.test.storageSize()                      返回此數據集的存儲大小
db.test.totalIndexSize()                   返回此數據集的索引文件大小
db.test.totalSize()                        返回些數據集的總大小
db.test.update(query,object[,upsert_bool]) 在此數據集中更新一條數據
db.test.validate()                         驗證此數據集
db.test.getShardVersion()                  返回數據集共享版本號

MongoDB語法與現有關系型數據庫SQL語法比較

MongoDB語法                <==>                   MySql語法
db.test.find({‘name‘:‘foobar‘}) <==> select * from test where name=‘foobar‘
db.test.find()                  <==> select * from test
db.test.find({‘ID‘:10}).count() <==> select count(*) from test where ID=10
db.test.find().skip(10).limit(20)     <==> select * from test limit 10,20
db.test.find({‘ID‘:{$in:[25,35,45]}}) <==> select * from test where ID in (25,35,45)
db.test.find().sort({‘ID‘:-1})        <==> select * from test order by ID desc
db.test.distinct(‘name‘,{‘ID‘:{$lt:20}})  <==> select distinct(name) from test where ID<20
db.test.group({key:{‘name‘:true},cond:{‘name‘:‘foo‘},reduce:function(obj,prev){prev.msum+=obj.marks;},initial:{msum:0}})  <==> select name,sum(marks) from test group by name
db.test.find(‘this.ID<20‘,{name:1})  <==> select name from test where ID<20
db.test.insert({‘name‘:‘foobar‘,‘age‘:25})<==>insert into test (‘name‘,‘age‘) values(‘foobar‘,25)
db.test.remove({})                <==> delete * from test
db.test.remove({‘age‘:20})        <==> delete test where age=20
db.test.remove({‘age‘:{$lt:20}})  <==> elete test where age<20
db.test.remove({‘age‘:{$lte:20}}) <==> delete test where age<=20
db.test.remove({‘age‘:{$gt:20}})  <==> delete test where age>20
db.test.remove({‘age‘:{$gte:20}}) <==> delete test where age>=20
db.test.remove({‘age‘:{$ne:20}})  <==> delete test where age!=20
db.test.update({‘name‘:‘foobar‘},{$set:{‘age‘:36}}) <==> update test set age=36 where name=‘foobar‘
db.test.update({‘name‘:‘foobar‘},{$inc:{‘age‘:3}})  <==> update test set age=age+3 where name=‘foobar‘

註意以上命令大小寫敏感。

每篇半小時1天入門MongoDB——2.MongoDB環境變量配置和Shell操作