MongoDB入門簡介|MongoDB下載安裝|MongoDB語法

atlantisholic發表於2011-11-10

第1章    MongoDB簡介

1.1    功能特點

    官方網址:http://www.mongodb.org/

    MongoDB是一個基於分散式檔案儲存的資料庫開源專案。由C++語言編寫,旨在為WEB應用提供可護展的高效能資料儲存解決方案。
    它的特點是可擴充套件,高效能,易使用,模式自由,儲存資料非常方便等,主要功能特性有:
    面向文件儲存:(類JSON資料模式簡單而強大)。
    高效的傳統儲存方式:支援二進位制資料及大型物件(如照片和視訊)。
    複製及自動故障轉移:Mongo資料庫支援伺服器之間的資料複製,支援主-從模式及伺服器之間的相互複製。
    Auto-Sharding自動分片支援雲級擴充套件性(處於早期alpha階段):自動分片功能支援水平的資料庫叢集,可動態新增額外的機器。
    動態查詢:它支援豐富的查詢表示式。查詢指令使用JSON形式的標記,可輕易查詢文件中內嵌的物件及陣列。
    全索引支援:包括文件內嵌物件及陣列。Mongo的查詢優化器會分析查詢表示式,並生成一個高效的查詢計劃。
    支援RUBY,PYTHON,JAVA,C++,PHP等多種語言。

1.2    適用範圍

適用場景:
    適合實時的插入,更新與查詢,並具備應用程式實時資料儲存所需的複製及高度伸縮性。
    適合作為資訊基礎設施的持久化快取層。
    適合由數十或數百臺伺服器組成的資料庫。因為Mongo已經包含對MapReduce引擎的內建支援。
    Mongo的BSON資料格式非常適合文件化格式的儲存及查詢。

不適用場景:
    高度事務性的系統。
    傳統的商業智慧應用。
    級為複雜的SQL查詢。
 

第2章MongoDB下載及安裝

2.1    下載地址

http://www.mongodb.org/downloads
選擇一個最新穩定的版本v1.6.5,如下圖:

2.2    安裝方法
通過mongod –install命令把mongodb註冊成為window service。

1)    建立資料庫儲存目錄;例如:d:\data\db

2)    通過命令列執行:
    mongod --bind_ip 127.0.0.1 --logpath d:\data\logs --logappend --dbpath d:\data\db
--directoryperdb –install

【注:將mongodb安裝成服務,裝該服務繫結到IP127.0.0.1,日誌檔案為d:\data\logs,以及新增方式記錄。資料目錄為d:\data\db。並且每個資料庫將儲存在一個單獨的目錄(--directoryperdb)】

3)    啟動服務後 ,嘗試是否可用,通過命令列進入%MONGODB_HOME%\bin下執行mongo.exe命令後出現如下圖所示資訊表示連線成功:
 

第3章    MongoDB語法

3.1    基本命令
3.1.1.    啟動mongodb
run 直接啟動:
例如:mongod run
 
--dbpath 指定儲存目錄啟動:
例如:mongod –dbpath = d:\ db
 
--port 指定埠啟動:(預設埠是:27017)
例如:mongod --port 12345。
3.1.2.    停止mongodb
在視窗模式中,可以直接使用Ctrl+C停止服務。

3.2    SQL語法
3.2.1.    基本操作
db.AddUser(username,password)  新增使用者
db.auth(usrename,password)     設定資料庫連線驗證
db.cloneDataBase(fromhost)     從目標伺服器克隆一個資料庫
db.commandHelp(name)           returns the help for the command
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)             run code server-side
db.getCollection(cname)        取得一個資料集合,同用法:db['cname'] or
db.getCollenctionNames()       取得所有資料集合的名稱列表
db.getLastError()              返回最後一個錯誤的提示訊息
db.getLastErrorObj()           返回最後一個錯誤的物件
db.getMongo()                  取得當前伺服器的連線物件get the server
db.getMondo().setSlaveOk()     allow this connection to read from then nonmaster membr of a replica pair
db.getName()                   返回當運算元據庫的名稱
db.getPrevError()              返回上一個錯誤物件
db.getProfilingLevel()         
db.getReplicationInfo()        獲得重複的資料
db.getSisterDB(name)           get the db at the same server as this onew
db.killOp()                    停止(殺死)在當前庫的當前操作
db.printCollectionStats()      返回當前庫的資料集狀態
db.printReplicationInfo()
db.printSlaveReplicationInfo()
db.printShardingStatus()       返回當前資料庫是否為共享資料庫
db.removeUser(username)        刪除使用者
db.repairDatabase()            修復當前資料庫
db.resetError()                
db.runCommand(cmdObj)          run a database command. if cmdObj is a string, turns it into {cmdObj:1}
db.setProfilingLevel(level)    0=off,1=slow,2=all
db.shutdownServer()            關閉當前服務程式
db.version()                   返回當前程式的版本資訊

3.2.2.    資料集(表)操作
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,)
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()                  返回資料集共享版本號

3.3.  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'

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/23071790/viewspace-710778/,如需轉載,請註明出處,否則將追究法律責任。

相關文章