天天看點

MongoDB 常用指令

安裝使用:

首先在Ubuntu上安裝MongoDB。

下載下傳MongoDB, 現在最新的生産版本1.7.0

1. 解壓檔案.

$ tar -xvf mongodb-linux-i686-1.4.3.tgz

2. 為MongoDB建立資料目錄,預設情況下它将資料存儲在/data/db

$ sudo mkdir -p /data/db/

$ sudo chown `id -u` /data/db

3. 啟動MongoDB服務.

$ cd mongodb-linux-i686-1.4.3/bin

$ ./mongod

4. 打開另一個終端,并確定你在MongoDB的bin目錄,輸入如下指令.

$ ./mongo

一些概念 

一個mongod服務可以有建立多個資料庫,每個資料庫可以有多張表,這裡的表名叫collection,每個collection可以存放多個文檔(document),每個文檔都以BSON(binary json)的形式存放于硬碟中,是以可以存儲比較複雜的資料類型。它是以單文檔為機關存儲的,你可以任意給一個或一批文檔新增或删除字段,而不會對其它文檔造成影響,這就是所謂的schema-free,這也是文檔型資料庫最主要的優點。跟一般的key-value資料庫不一樣的是,它的value中存儲了結構資訊,是以你又可以像關系型資料庫那樣對某些域進行讀寫、統計等操作。Mongo最大的特點是他支援的查詢語言非常強大,其文法有點類似于面向對象的查詢語言,幾乎可以實作類似關系資料庫單表查詢的絕大部分功能,而且還支援對資料建立索引。Mongo還可以解決海量資料的查詢效率,根據官方文檔,當資料量達到50GB以上資料時,Mongo資料庫通路速度是MySQL10 倍以上。

BSON

BSON是Binary JSON 的簡稱,是一個JSON文檔對象的二進制編碼格式。BSON同JSON一樣支援往其它文檔對象和數組中再插入文檔對象和數組,同時擴充了JSON的資料類型。如:BSON有Date類型和BinDate類型。

BSON被比作二進制的交換格式,如同Protocol Buffers,但BSON比它更“schema-less”,非常好的靈活性但空間占用稍微大一點。

BSON有以下三個特點:

1.  輕量級

2.  跨平台

3.  效率高

命名空間

MongoDB存儲BSON對象到collections,這一系列的資料庫名和collection名被稱為一個命名空間。如同:java.util.List;用來管理資料庫中的資料。

索引 

mongodb可以對某個字段建立索引,可以建立組合索引、唯一索引,也可以删除索引,建立索引就意味着增加空間開銷。預設情況下每個表都會有一個唯一索引:_id,如果插入資料時沒有指定_id,服務會自動生成一個_id,為了充分利用已有索引,減少空間開銷,最好是自己指定一個unique的key為_id,通常用對象的ID比較合适,比如商品的ID。

shell操作資料庫:

  1.  超級使用者:

        1. #進入資料庫admin

          use admin

        2. #增加或修改使用者密碼

         db.addUser('name','pwd')

        3. #檢視使用者清單

         db.system.users.find()

        4. #使用者認證

         db.auth('name','pwd')

        5. #删除使用者

         db.removeUser('name')

        6. #檢視所有使用者

         show users

        7. #檢視所有資料庫

         show dbs

        8. #檢視所有的collection

         show collections

        9. #檢視各collection的狀态

         db.printCollectionStats()

       10. #檢視主從複制狀态

         db.printReplicationInfo()

       11. #修複資料庫

         db.repairDatabase()

       12. #設定記錄profiling,0=off 1=slow 2=all

         db.setProfilingLevel(1)

       13. #檢視profiling

         show profile

       14. #拷貝資料庫

         db.copyDatabase('mail_addr','mail_addr_tmp')

       15. #删除collection

         db.mail_addr.drop()

       16. #删除目前的資料庫

         db.dropDatabase()

       17. 備份資料庫

         mongodump -h localhost:27017 -d dataname -o /data/dump

       18. 恢複資料庫

         mongorestore -d dataname /data/dump

       19. 備份資料庫表

         mongodump -h localhost:27017 -d dataname -c tablename -o /data/dump

       20. 恢複資料庫表

         mongorestore -d dataname -c tablename /data/dump

         mongorestore -h host:port -d dataname --collection tablename ./tmpdump/some.bson

  2. 增删改

        1. #存儲嵌套的對象

           db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})

        2. #存儲數組對象

           db.user_addr.save({'Uid':'[email protected]','Al':['[email protected]','[email protected]']})

        3. #根據query條件修改,如果不存在則插入,允許修改多條記錄

           db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)

        4. #删除yy=5的記錄

           db.foo.remove({'yy':5})

        5. #删除所有的記錄

           db.foo.remove()

  3. 索引

        1. #增加索引:1(ascending),-1(descending)

        2. db.foo.ensureIndex({firstname: 1, lastname: 1}, {unique: true, dropDups: true });  

        3. #索引子對象

        4. db.user_addr.ensureIndex({'Al.Em': 1})

        5. #檢視索引資訊

        6. db.foo.getIndexes()

        7. db.foo.getIndexKeys()

        8. #根據索引名删除索引

        9. db.user_addr.dropIndex('Al.Em_1')

  4. 查詢

        1. #查找所有

       2. db.foo.find()

       3. #查找一條記錄

       4. db.foo.findOne()

       5. #根據條件檢索10條記錄

       6. db.foo.find({'msg':'Hello 1'}).limit(10)

       7. #sort排序

       8. db.deliver_status.find({'From':'[email protected]'}).sort({'Dt',-1})

        9. db.deliver_status.find().sort({'Ct':-1}).limit(1)

       10. #count操作

       11. db.user_addr.count()

       12. #distinct操作,查詢指定列,去重複

       13. db.foo.distinct('msg')

       14. #”>=”操作

       15. db.foo.find({"timestamp": {"$gte" : 2}})

       16. #子對象的查找

       17. db.foo.find({'address.city':'beijing'})

  5. 管理

        1. #檢視collection資料的大小

        2. db.deliver_status.dataSize()

        3. #檢視colleciont狀态

        4. db.deliver_status.stats()

        5. #查詢所有索引的大小

        6. db.deliver_status.totalIndexSize()

5.  進階查詢

條件操作符 

$gt : > 

$lt : < 

$gte: >= 

$lte: <= 

$ne : !=、<> 

$in : in 

$nin: not in 

$all: all 

$not: 反比對(1.3.3及以上版本)

查詢 name <> "bruce" and age >= 18 的資料 

db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});

查詢 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的資料 

db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});

查詢 age in (20,22,24,26) 的資料 

db.users.find({age: {$in: [20,22,24,26]}});

查詢 age取模10等于0 的資料 

db.users.find('this.age % 10 == 0'); 

或者 

db.users.find({age : {$mod : [10, 0]}});

比對所有 

db.users.find({favorite_number : {$all : [6, 8]}}); 

可以查詢出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } 

可以不查詢出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }

查詢不比對name=B*帶頭的記錄 

db.users.find({name: {$not: /^B.*/}}); 

查詢 age取模10不等于0 的資料 

db.users.find({age : {$not: {$mod : [10, 0]}}});

#傳回部分字段 

選擇傳回age和_id字段(_id字段總是會被傳回) 

db.users.find({}, {age:1}); 

db.users.find({}, {age:3}); 

db.users.find({}, {age:true}); 

db.users.find({ name : "bruce" }, {age:1}); 

0為false, 非0為true

選擇傳回age、address和_id字段 

db.users.find({ name : "bruce" }, {age:1, address:1});

排除傳回age、address和_id字段 

db.users.find({}, {age:0, address:false}); 

db.users.find({ name : "bruce" }, {age:0, address:false});

數組元素個數判斷 

對于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }記錄 

比對db.users.find({favorite_number: {$size: 3}}); 

不比對db.users.find({favorite_number: {$size: 2}});

$exists判斷字段是否存在 

查詢所有存在name字段的記錄 

db.users.find({name: {$exists: true}}); 

查詢所有不存在phone字段的記錄 

db.users.find({phone: {$exists: false}});

$type判斷字段類型 

查詢所有name字段是字元類型的 

db.users.find({name: {$type: 2}}); 

查詢所有age字段是整型的 

db.users.find({age: {$type: 16}});

對于字元字段,可以使用正規表達式 

查詢以字母b或者B帶頭的所有記錄 

db.users.find({name: /^b.*/i});

$elemMatch(1.3.1及以上版本) 

為數組的字段中比對其中某個元素

Javascript查詢和$where查詢 

查詢 age > 18 的記錄,以下查詢都一樣 

db.users.find({age: {$gt: 18}}); 

db.users.find({$where: "this.age > 18"}); 

db.users.find("this.age > 18"); 

f = function() {return this.age > 18} db.users.find(f);

排序sort() 

以年齡升序asc 

db.users.find().sort({age: 1}); 

以年齡降序desc 

db.users.find().sort({age: -1});

限制傳回記錄數量limit() 

傳回5條記錄 

db.users.find().limit(5); 

傳回3條記錄并列印資訊 

db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); 

結果 

my age is 18 

my age is 19 

my age is 20

限制傳回記錄的開始點skip() 

從第3條記錄開始,傳回5條記錄(limit 3, 5) 

db.users.find().skip(3).limit(5);

查詢記錄條數count() 

db.users.find().count(); 

db.users.find({age:18}).count(); 

以下傳回的不是5,而是user表中所有的記錄數量 

db.users.find().skip(10).limit(5).count(); 

如果要傳回限制之後的記錄數量,要使用count(true)或者count(非0) 

db.users.find().skip(10).limit(5).count(true);

分組group() 

假設test表隻有以下一條資料 

, invoked_at: {d:"2009-11-03", t:"17:14:05"} 

, response_time: 0.05 

, http_action: "GET /display/DOCS/Aggregation" 

使用group統計test表11月份的資料count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; 

db.test.group( 

{ cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} 

, key: {http_action: true} 

, initial: {count: 0, total_time:0} 

, reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } 

, finalize: function(out){ out.avg_time = out.total_time / out.count } 

} );

"http_action" : "GET /display/DOCS/Aggregation", 

"count" : 1, 

"total_time" : 0.05, 

"avg_time" : 0.05 

]

本文轉自 ponpon_ 51CTO部落格,原文連結:http://blog.51cto.com/liuxp0827/1355869,如需轉載請自行聯系原作者