MongoDB入門簡介----1

MongoDB入門簡介

1.  功能特點 


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

    MongoDB是一個基於分佈式文件存儲的數據庫開源項目。由C++語言編寫,旨在爲WEB應用提供可護展的高性能數據存儲解決方案。
    它的特點是可擴展,高性能,易使用,模式自由,存儲數據非常方便等,主要功能特性有:
    面向文檔存儲:(類JSON數據模式簡單而強大)。
    高效的傳統存儲方式:支持二進制數據及大型對象(如照片和視頻)。
    複製及自動故障轉移:Mongo數據庫支持服務器之間的數據複製,支持主-從模式及服務器之間的相互複製。
    Auto-Sharding自動分片支持雲級擴展性(處於早期alpha階段):自動分片功能支持水平的數據庫集羣,可動態添加額外的機器。
    動態查詢:它支持豐富的查詢表達式。查詢指令使用JSON形式的標記,可輕易查詢文檔中內嵌的對象及數組。
    全索引支持:包括文檔內嵌對象及數組。Mongo的查詢優化器會分析查詢表達式,並生成一個高效的查詢計劃。

    支持RUBY,PYTHON,JAVA,C++,PHP等多種語言。

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,<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()                  返回數據集共享版本號

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'



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章