Mongo 資料庫 基本操作

2112511463發表於2014-11-14


配置yum源安裝
cat /etc/yum.repos.d/10gen.repo 
[10gen]
name=10gen
baseurl=
gpgcheck=0
enabled=1
yum install mongodb-org -y


原始碼包下載安裝
#wget  
#tar –zxvf mongodb-linux-x86_64-2.4.9.tgz
#mv mongodb-linux-x86_64 /usr/local/mongdb


配置mongodb
#groupadd mongodb
#useradd mongodb –g mongodb
#mkdir –p /mongodb/data/
# mkdir –p /mongodb/log/
#chown –R mongodb:mongodb mongodb
 
啟動
[root@wch ~]# /usr/local/mongodb/bin/mongod --dbpath=/mongodb/data/ --logpath=/mongodb/log/
檢視所有資料庫
> show dbs
admin   0.203125GB ...

建立資料庫
> use wch  (這步還沒算建成 要對資料庫進行操作後才算成功)
給當前資料庫建立普通讀寫使用者
> db.addUser('wch','123456')
給當前資料庫建立只讀使用者
> db.addUser('wch','123456',true) 
使用者認證
> db.auth('wch','123456')
1 (“1”為認證成功,“0”為不成功)
檢視當前資料庫的所有使用者
> db.system.users.find()
修改使用者密碼
進入對應的資料庫
>db.changeUserPassword('root','passwd')
檢視當前資料庫狀態
db.stats()
刪除資料庫使用者
> db.system.users.remove({user:"wch"})
刪除當前資料庫
> use atest
> db.dropDatabase()
{ "dropped" : "atest", "ok" : 1 }
 
給資料庫建表,插入資訊
(當插入表的主鍵“_id”一樣時,後者會將將前者覆蓋)
> db.sa.save({name:"wang",age:22})
> db.sa.save({_id:001,name:"wang",age:22})
> db.sa.save({_id:001,name:"www",age:21,info:{x:201,y:205}})
 
查詢表
> db.sa.find()
{ "_id" : ObjectId("52e1cb7b7f2219fee1443fa2"), "name" : "wang", "age" : 22 }
{ "_id" : 1, "name" : "www", "age" : 21, "info" : { "x" : 201, "y" : 205 } }
查詢表資訊後排序
查詢後以“name”為關鍵字順序排序
> db.sa.find().sort({name:1}) // select * from sa order by x asc
倒序排序
> db.sa.find().sort({name:-1}) // select * from sa order by x desc
排序後,跳過過skip()個資訊向下查詢limit()個
> db.sa.find().sort({name:1}).skip(1).limit(2) // select * from sa order by x asc limit 1,2
 
查詢
> db.sa.find({name:"wg"}) // select * from coll where name=wg
> db.sa.find({age:{$lt:22}}) // select * from sa where age < 22
> db.sa.find({},{age:true}) // select age from sa
 
修改資訊
> db.sa.update({name:'www'},{$set:{age:27}}) //update sa set age=27 where name=’www’
> db.sa.update({name:'wg'},{$inc:{age:2}})  //update sa set age=age+2 where name=’wg’
 
刪行
> db.sa.remove({_id:1}) //delete * from sa where id=1
 
資料庫備份
[root@wch ~]# /usr/local/mongodb/bin/mongodump -d test -o /tmp/
-d:指定資料庫
-o:指定匯出到的路徑
 
資料庫恢復
[root@wch test]# /usr/local/mongodb/bin/mongorestore -d test /tmp/test/
 
匯出()
[root@wch test]# /usr/local/mongodb/bin/mongoexport -d test -c sa -o /sa.dat
匯入
[root@wch test]# /usr/local/mongodb/bin/mongoimport -d test -c sa /sa.dat 

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

相關文章