標籤:mongo 資料庫 操作
mongodb使用
安裝mongodb,並啟動mongodb後,基本操作:
show dbs; 顯示資料庫show collections;顯示當前資料庫中的集合,類似mysql中資料庫的表show users; 顯示使用者use <db name> 切換當前資料庫,與mysql中一樣
資料庫常用命令:
MongoDB沒有建立資料庫的命令,但有類似的命令,先運行use <db name> 命令,之後就做一些操作,如db.createCollection(‘user‘),這樣就可以建立一個資料庫了。刪除當前使用的資料庫: db.dropDatabase();從指定的主機上複製資料庫: db.cloneDatabase(‘hostname/ip‘);從指定的機器上複製指定的資料庫到某個資料庫 db.copyDatabase(‘mydb‘,‘temp‘,‘127.0.0.1:27017‘)修複當前資料庫: db.repairDatabase();查看當前使用的資料庫: db.getName() / db顯示當前db狀態 db.stats()當前db版本 db.version()查看當前db的連結機器的地址 db.getMongo()
Collection集合常用命令:
建立一個集合: db.createCollection(‘name‘, {capped:<Boolean>,autoIndexId:<Boolean>,size:<number>,max:<number>}) name:是集合的名字, capped: 是否啟用集合限制,如果啟用需要制定一個限制條件,預設不啟用,這個參數沒有實際意義 size:限制集合使用空間的大小,預設沒有限制 max:集合中最大條數限制,預設為沒有限制 autoIndexId: 是否使用id作為索引,預設使用(true/false) size 的優先順序比max高比如: 1、db.createCollection(‘log‘) 沒有任何的大小,數量限制,使用_id作為預設索引 2、限制集合空間的大小:db.createCollection(‘log‘,{size:1024}) 或db.createCollection(‘log‘,{capped:true,size:1024}),限制空間大小為1M,如果超出1M,則會刪除最早的記錄 3、限制集合的最大條數: db.createCollection(‘log‘,{max:1024}),建立一個名字為log集合,最大條數為1024,超過則會刪除最早的一條記錄,這個不能使用capped:true,否則會報錯 4、限制最大條數有限制使用空間大小,db.createCollection(‘log‘,{size:1024,max:1024})或 db.createCollection(‘log‘,{capped:true,size:1024,max:1024}) 限制集合最大使用空間為1M,最大條數為1024條 得到指定名稱的集合 db.getCollection(‘one‘)得到當前db的所有集合 db.getCollectionNames()顯示當前db所有集合索引的狀態 db.printCollectionStats()
使用者相關相關操作:
Mongodb使用者和認證 許可權總結:新安裝mongodb後開啟MongoDB服務時不添加任何參數時,預設是沒有許可權驗證的,登入的使用者可以對資料庫任意操作而且可以遠端存取資料庫。此時,mongodb預設有一個admin資料庫,並且是空的,沒有記錄許可權相關的資訊。當admin.system.users一個使用者都沒有時,即使mongodb啟動時添加了--auth參數,如果沒有在admin資料庫中添加使用者,此時不進行任何認證還是可以做任何操作。直到admin.system.users中添加了一個使用者。需要注意的是:admin.system.users中將會儲存比在其它資料庫中設定的使用者權限更大的使用者資訊,擁有超級許可權,也就是說在admin中建立的使用者可以對mongodb中的其他資料庫資料進行操作。1、mongodb系統中,資料庫是由超級使用者來建立的,一個資料庫可以包含多個使用者,一個使用者只能在一個資料庫下,不同資料庫中的使用者可以同名!2、當admin.system.users一個使用者都沒有時,即使mongod啟動時添加了--auth參數,如果沒有在admin資料庫中添加使用者,此時不進行任何認證還是可以做任何操作(不管是否是以--auth 參數啟動),直到在admin.system.users中添加了一個使用者。3、特定資料庫比如DB1下的使用者User1,不能夠訪問其他資料庫DB2,但是可以訪問本資料庫下其他使用者建立的資料!4、不同資料庫中同名的使用者不能夠登入其他資料庫!比如DB1,DB2都有user1,以user1登入DB1後,不能夠登入到DB2進行資料庫操作!5、在admin資料庫建立的使用者具有超級許可權,可以對mongodb系統內的任何資料庫的資料對象進行操作!
使用者相關命令操作:
添加一個使用者:db.addUser(‘name‘)或 db.addUser(‘username‘,‘passwd123‘,true) 添加使用者,設定密碼,是否為唯讀,預設為false資料庫認證、安全模式 db.auth(‘username‘,‘passwd‘)顯示當前所有使用者: show users;刪除使用者: db.removeUser(‘username‘)
集合查詢:
查詢所有記錄:db.userInfo.find() 相當於:select * from userInfo;預設每頁顯示20條記錄,當顯示不下的情況下,可以用it迭代命令查詢下一頁,it後面不要加;可以設定每頁顯示資料的大小,用DBQuery.shellBatchSize= 50;這樣每頁就顯示50條記錄了查詢去掉集合中的某列的重複資料db.userInfo.distinct(‘name‘) 相當於:select distict name from userInfo;查詢age=xx的記錄db.userInfo.find({‘age‘:22})查詢age>22的記錄:db.userInfo.find({age:{$gt:22}}) 相當於:select * from userInfo where age >22;查詢age<22的記錄:db.userInfo.find({age:{$lt:22}})查詢age >= 25的記錄db.userInfo.find({age:{$gte:25}})查詢age <= 25的記錄db.userInfo.find({age:{$lte:25}})查詢age >= 23 並且 age <= 26db.userInfo.find({age:{$gte:23,$lte:26}})查詢name中包含mongo的資料db.userInfo.find({name: /mongo/}) 相當於:select * from userInfo where name like ‘%mongo%’;查詢name中以mongo開頭的db.userInfo.find({name:/^mongo/}) 相當於:select * from userInfo where name like ‘mongo%’;查詢指定列name,age資料:db.userInfo.find({},{name:1,age:1}) 相當於:select name, age from userInfo;當然name也可以用true或false,當用true的情況下,如例子一樣的效果,如果為false就排除name,顯示name以外的列的資訊。查詢指定列name、age資料, age > 25db.userInfo.find({age:{$gt:25}},{name:1,age:1})查詢name = zhangsan, age = 22的資料db.userInfo.find({name:‘zhangsan‘,age:22})查詢10條以後的資料db.userInfo.find().skip(10) 相當於:select * from userInfo where id not in (selecttop 10 * from userInfo);查詢在5-10之間的資料db.userInfo.find().limt(10).skip(5)可用於分頁,limit是pageSize,skip是第幾頁*pageSizeand 查詢db.userInfo({‘name‘:‘hurry‘,‘age‘:18},{‘name‘:1,‘age‘:1}) 相當於:select name,age from userInfo where name=‘hurry‘or與查詢db.userInfo.find({$or: [{age:22},{age:25}]}) 相當於:select * from userInfo where age = 22 or age = 25;使用in,not in ($in,$nin)db.userInfo.find({‘age‘:{$in:[10,22,26]}}) 相當於:select * from users where age in (10, 22, 26);與null匹配db.userInfo.find({‘age‘:null})查詢第一條資料:db.userInfo.findOne() 相當於:selecttop 1 * from userInfo;或:db.userInfo.find().limit(1)查詢某個結果集的記錄條數:db.userInfo.find({age:{$gte:25}}).count() 相當於:select count(*) from userInfo where age >= 25;按照某列進行求和:db.userInfo.find({sex:{$exists:true}}).count() 相當於select count(sex) from userInfo;
大於,小於,大於或等於,小於或等於$gt:大於$lt:小於$gte:大於或等於$lte:小於或等於不等於:$ne模數運算:$moddb.userInfo.find({‘a‘:{$mod:[10,1]}})$all$all 與$in類似,但是他需要匹配條件內所有的值:如一個對象:{a:[1,2,3]}這個條件可以匹配:db.userInfo.find(a:{$all:[2,3]})但是這個條件就不行了,db.userInfo.find(a:{$all:[2,3,4]})$size 是匹配數組內的元素數量的如一個對像:{a:[‘foo‘]}這個語句就可以匹配:db.userInfo.find({a:{$size:1}})官網上說不能用來匹配一個範圍內的元素,如果想找$size<5之類的,他們建議建立一個$exists$exists用來判斷一個元素是否存在如下:db.userInfo.find({a:{$exists:true}}) 如果存在a就返回db.userInfo.find({a:{$exists:false}}) 如果不存在元素a 就返回$not取反db.userInfo.find({‘name‘:{$not:/acme.*corp/i}})$type$type基於bson type來匹配一個元素的類型,像是按照ID來匹配,bson類型和id對照表:
類型描述 |
類型值 |
Double |
1 |
String |
2 |
Object |
3 |
Array |
4 |
Binary data |
5 |
Object id |
7 |
Boolean |
8 |
Date |
9 |
Null |
10 |
Regular expression |
11 |
JavaScript code |
13 |
Symbol |
14 |
JavaScript code with scope |
15 |
32-bit integer |
16 |
Timestamp |
17 |
64-bit integer |
18 |
Min key |
255 |
Max key |
127 |
使用如下:
db.userInfo.find({a:{$type:2}}) 如果是字串即:string就返回adb.userInfo.find({a:{$type:16}}) 如果是int類型,就返回a
Regex
mongo支援Regex,如db.userInfo.find({name:/acme.*corp/i}) 後面i的意思是區分大小寫
索引:
建立索引:db.userInfo.ensureIndex({name:1})db.userInfo.ensureIndex({name:1,ts:-1})查詢當前集合所有索引:db.userInfo.getIndexes()查看總索引記錄大小db.userInfo.totalIndexSize()讀取當前集合所有index資訊db.userInfo.reIndex()刪除指定索引:db.userInfo.dropIndex("name_1")刪除所有索引db.userInfo.dropIndexes()
添加:
db.userInfo.save({‘name‘:‘zhangsan‘,‘age‘:25,sex:true})添加的資料的資料列,沒有固定,根據添加的資料為準
修改:
db.userInfo.update({age:25},{$set:{name:‘lisi‘}},false,true)相當於:update users set name = ‘changeName’ where age = 25;db.userInfo.update({name:‘lisi‘},{$inc:{age:50}},false,true)相當於:update users set age = age + 50 where name = ‘lisi’;db.userInfo.update({‘name‘:‘lisi‘},{$inc:{‘age‘:50},$set:{name:‘hoho‘}},false,true)
刪除:
db.userInfo.remove({‘age‘: 132})
查詢修改刪除:
db.userInfo.findAndModify({query:{age:{$gte:25}},sort:{age:-1},update:{$set:{name:‘a2‘},$inc:{age:2}},remove:true})db.runCommand({findandmodify:‘usersInfo‘,query: {age:{$gte:25}},sort: {age:-1},update:{$set:{name:‘a2‘},$inc:{age:2}},remove:true})update 或 remove 其中一個是必須的參數; 其他參數可選。
排序:
升序:db.userInfo.find().sort({age:1})降序:db.userInfo.find().sort({age:-1})
將一個對象轉換成json
tojson(new Object())tojson(new Ojbect(‘a‘))
迴圈添加資料:
> for (var i = 0; i < 30; i++) {db.userInfo.save({name:‘u_‘ + i, age:22 + i,sex:i % 2})}這樣就迴圈添加了30條資料,同樣也可以省略括弧的寫法> for (var i = 0; i < 30; i++) {db.userInfo.save({name:‘u_‘+i,age:22+i,sex:i%2})}
find 遊標查詢
> var cursor = db.userInfo.find()> while (cursor.hasNext()) {printjson(cursor.next())}這樣就查詢所有的users資訊,同樣可以這樣寫var cursor = db.users.find();while (cursor.hasNext()) {printjson(cursor.next)}
forEach迭代迴圈
db.users.find().forEach(printjson)forEach中必須傳遞一個函數來處理每條迭代的資料資訊
將find遊標當數組處理
var cursor = db.users.find()cursor[4]取得下標索引為4的那條資料既然可以當做數組處理,那麼就可以獲得它的長度:cursor.length();或者cursor.count();那樣我們也可以用迴圈顯示資料for (var i = 0 ,len = c.length(); i < len; i++) printjson(c[i])將find遊標轉換成數組>var arr = db.userInfo.find().toArray()>printjson(arr[2])用toArray方法將其轉換為數組
其他:
查詢之前的錯誤資訊:db.getPrevError();清除錯誤記錄:db.resetError()
本文出自 “linux學習” 部落格,轉載請與作者聯絡!
Mongodb常用操作