啟動MongoDB
$mongod --fork --logpath=/data/log/r3.log
--fork 允許mongod后臺運行,但是必須指定日志記錄文件路徑(Enables a daemon mode that runs the mongos process in the background.)
--logpath 指定日志記錄文件路徑
導出Collections
$mongoexport -d test -c user -o user.dat
-d 指定數據庫
-c 指定collections
-o 指定輸出文件名稱
導出Collections為CSV格式
$mongoexport -d test -c user --csv -f uid,username,age -o user_csv.dat
-f 指明需要導出哪些列
—-csv 指明導出格式為CSV
導入Collections
$mongoimport -d test -c user user.dat
導入CSV文件
$mongoimport -d test -c user --type csv --headerline --file user_csv.dat
-type 指明要導入的文件格式
-headerline 批明不導入第一行,因為第一行是列名
-file 指明要導入的文件路徑
數據庫備份
$ mongodump -d test
2016-02-19T16:44:20.538+0800 writing test.things to
2016-02-19T16:44:20.538+0800 writing test.students to
2016-02-19T16:44:20.538+0800 writing test.fs.chunks to
2016-02-19T16:44:20.538+0800 writing test.thins to
2016-02-19T16:44:20.539+0800 done dumping test.thins (9 documents)
2016-02-19T16:44:20.539+0800 done dumping test.things (20 documents)
2016-02-19T16:44:20.540+0800 done dumping test.students (8 documents)
2016-02-19T16:44:20.540+0800 writing test.user to
2016-02-19T16:44:20.540+0800 writing test.fs.files to
2016-02-19T16:44:20.540+0800 writing test.students_res to
2016-02-19T16:44:20.541+0800 done dumping test.fs.files (1 document)
2016-02-19T16:44:20.541+0800 done dumping test.students_res (1 document)
2016-02-19T16:44:20.541+0800 done dumping test.user (2 documents)
2016-02-19T16:44:20.544+0800 done dumping test.fs.chunks (5 documents)
也可以加入-o path_to_dump來指定備份的目錄
數據庫恢復
$ mongorestore -d test dump/*
**如果想恢復數據庫,可以不用先刪除數據庫,可以在命令后面加入-drop來刪除表,然后再想表中插入數據
查看數據庫正在做什么
db.currentOp();
創建數據庫
MongoDB沒有創建數據庫的命令,可以直接使用use test來創建test數據庫
創建Collcetion
db.createCollection("questions");
MongoDB實時監控
此工具可以快速的查看某組運行中的 MongoDB 實例的統計信息
$mongostat
insert: 每秒插入量
query: 每秒查詢量
update: 每秒更新量
delete: 每秒刪除量
locked: 鎖定量
qr | qw: 客戶端查詢排隊長度(讀|寫)
ar | aw: 活躍客戶端量(讀|寫)
conn: 連接數 time: 當前時間
刪除重復數據,建立索引(MongoDB 2.x)
coll.ensureIndex({productid:1}) // 在productid上建立普通索引
coll.ensureIndex({district:1, plate:1}) // 多字段索引
coll.ensureIndex({productid:1}, {unique:true}) // 唯一索引
coll.ensureIndex({productid:1}, {unique:true, dropDups:true}) // 建索引時,如果遇到索引字段值已經出現過的情況,則刪除重復記錄
coll.getIndexes() // 查看索引
coll.dropIndex({productid:1}) // 刪除單個索
db.users.dropIndex({uid:1});
db.users.ensureIndex({uid:1, name:1}, {unique:true, dropDups:true});