溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

MongoDB中有哪些常用命令

發(fā)布時間:2021-06-24 15:40:41 來源:億速云 閱讀:150 作者:Leah 欄目:云計算

MongoDB中有哪些常用命令,相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

安裝使用:

首先在Ubuntu上安裝MongoDB。

下載MongoDB, 現(xiàn)在最新的生產(chǎn)版本1.7.0

1. 解壓文件.

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

2. 為MongoDB創(chuàng)建數(shù)據(jù)目錄,默認情況下它將數(shù)據(jù)存儲在/data/db

$ sudo mkdir -p /data/db/

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

3. 啟動MongoDB服務(wù).

$ cd mongodb-linux-i686-1.4.3/bin

$ ./mongod

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

$ ./mongo

一些概念 
一個mongod服務(wù)可以有建立多個數(shù)據(jù)庫,每個數(shù)據(jù)庫可以有多張表,這里的表名叫collection,每個collection可以存放多個文檔(document),每個文檔都以BSON(binary json)的形式存放于硬盤中,因此可以存儲比較復(fù)雜的數(shù)據(jù)類型。它是以單文檔為單位存儲的,你可以任意給一個或一批文檔新增或刪除字段,而不會對其它文檔造成影響,這就是所謂的schema-free,這也是文檔型數(shù)據(jù)庫最主要的優(yōu)點。跟一般的key-value數(shù)據(jù)庫不一樣的是,它的value中存儲了結(jié)構(gòu)信息,所以你又可以像關(guān)系型數(shù)據(jù)庫那樣對某些域進行讀寫、統(tǒng)計等操作。Mongo最大的特點是他支持的查詢語言非常強大,其語法有點類似于面向?qū)ο蟮牟樵冋Z言,幾乎可以實現(xiàn)類似關(guān)系數(shù)據(jù)庫單表查詢的絕大部分功能,而且還支持對數(shù)據(jù)建立索引。Mongo還可以解決海量數(shù)據(jù)的查詢效率,根據(jù)官方文檔,當(dāng)數(shù)據(jù)量達到50GB以上數(shù)據(jù)時,Mongo數(shù)據(jù)庫訪問速度是MySQL10 倍以上。

BSON

BSON是Binary JSON 的簡稱,是一個JSON文檔對象的二進制編碼格式。BSON同JSON一樣支持往其它文檔對象和數(shù)組中再插入文檔對象和數(shù)組,同時擴展了JSON的數(shù)據(jù)類型。如:BSON有Date類型和BinDate類型。

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

BSON有以下三個特點:

1.  輕量級

2.  跨平臺

3.  效率高

命名空間

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

索引 
mongodb可以對某個字段建立索引,可以建立組合索引、唯一索引,也可以刪除索引,建立索引就意味著增加空間開銷。默認情況下每個表都會有一個唯一索引:_id,如果插入數(shù)據(jù)時沒有指定_id,服務(wù)會自動生成一個_id,為了充分利用已有索引,減少空間開銷,最好是自己指定一個unique的key為_id,通常用對象的ID比較合適,比如商品的ID。

shell操作數(shù)據(jù)庫:

   1.  超級用戶:

         1. #進入數(shù)據(jù)庫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. #查看所有數(shù)據(jù)庫

          show dbs

         8. #查看所有的collection

          show collections

         9. #查看各collection的狀態(tài)

          db.printCollectionStats()

        10. #查看主從復(fù)制狀態(tài)

          db.printReplicationInfo()

        11. #修復(fù)數(shù)據(jù)庫

          db.repairDatabase()

        12. #設(shè)置記錄profiling,0=off 1=slow 2=all

          db.setProfilingLevel(1)

        13. #查看profiling

          show profile

        14. #拷貝數(shù)據(jù)庫

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

        15. #刪除collection

          db.mail_addr.drop()

        16. #刪除當(dāng)前的數(shù)據(jù)庫

          db.dropDatabase()

        17. 備份數(shù)據(jù)庫

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

        18. 恢復(fù)數(shù)據(jù)庫

          mongorestore -d dataname /data/dump

        19. 備份數(shù)據(jù)庫表

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

        20. 恢復(fù)數(shù)據(jù)庫表

          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. #存儲數(shù)組對象

            db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})

         3. #根據(jù)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. #根據(jù)索引名刪除索引

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

   4. 查詢

         1. #查找所有

        2. db.foo.find()

        3. #查找一條記錄

        4. db.foo.findOne()

        5. #根據(jù)條件檢索10條記錄

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

        7. #sort排序

        8. db.deliver_status.find({'From':'ixigua@sina.com'}).sort({'Dt',-1})

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

        10. #count操作

        11. db.user_addr.count()

        12. #distinct操作,查詢指定列,去重復(fù)

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

        14. #”>=”操作

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

        16. #子對象的查找

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

   5. 管理

         1. #查看collection數(shù)據(jù)的大小

         2. db.deliver_status.dataSize()

         3. #查看colleciont狀態(tài)

         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 的數(shù)據(jù) 
db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});

查詢 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的數(shù)據(jù) 
db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});

查詢 age in (20,22,24,26) 的數(shù)據(jù) 
db.users.find({age: {$in: [20,22,24,26]}});

查詢 age取模10等于0 的數(shù)據(jù) 
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 的數(shù)據(jù) 
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});

數(shù)組元素個數(shù)判斷 
對于{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及以上版本) 
為數(shù)組的字段中匹配其中某個元素

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});

限制返回記錄數(shù)量limit() 
返回5條記錄 
db.users.find().limit(5); 
返回3條記錄并打印信息 
db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); 
結(jié)果 
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);

查詢記錄條數(shù)count() 
db.users.find().count(); 
db.users.find({age:18}).count(); 
以下返回的不是5,而是user表中所有的記錄數(shù)量 
db.users.find().skip(10).limit(5).count(); 
如果要返回限制之后的記錄數(shù)量,要使用count(true)或者count(非0) 
db.users.find().skip(10).limit(5).count(true);

分組group() 
假設(shè)test表只有以下一條數(shù)據(jù) 
{ domain: "www.mongodb.org" 
, invoked_at: {d:"2009-11-03", t:"17:14:05"} 
, response_time: 0.05 
, http_action: "GET /display/DOCS/Aggregation" 

使用group統(tǒng)計test表11月份的數(shù)據(jù)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 

]

看完上述內(nèi)容,你們掌握 MongoDB中有哪些常用命令的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI