mongodb 是一個面向文檔可擴充的高性能開源資料庫,典型的應用場景有網頁資料,緩存,代替文檔存儲等。
指令的記憶和使用是一門基本功,這裡準備了速查表,可以做案頭手冊。
<col>
庫操作
切換或使用資料庫
use mymongodb
看所有的庫
show dbs
删除目前使用資料庫
db.dropdatabase()
克隆所有的庫到目前連接配接
db.clonedatabase(“192.160.1.1”)
複制指定的庫
db.clonedatabase(“sourcedb”,”targetdb”,”192.168.1.1”)
檢視目前資料庫
db.getname()
目前 資料庫 狀态
db.stats()
目前資料庫版本
db.version()
檢視目前資料庫的連接配接
db.getmongo()
使用者操作
添加使用者
db.adduser(“user_name”, “password”, true)
使用者認證
db.auth(“username”, “password”)
顯示所有使用者
show users;
删除使用者
db.removeuser(“username”);
集合基本資訊
查詢集合的資料條數
db.mycollection.count();
檢視資料空間大小
db.mycollection.datasize();
檢視集合所在的資料庫
db.mycollection.getdb();
目前聚集的狀态
db.mycollection.stats();
目前集合的總大小
db.mycollection.totalsize();
集合儲存空間大小
db.mycollection.storagesize();
shard版本資訊
db.mycollection.getshardversion();
集合重命名
db.mycollection.renamecollection(“targetcollection”);
删除集合
db.mycollection.drop();
集合資料增删改
添加記錄
db.mycollection.save({mykey:”t_key”,myvalue:”t-value”});
删除記錄
db.mycollection.remove({mykey:”t_key”});
修改記錄
db.mycollection.update({condition: xx}, {$set: {field: ‘changefield’}}, false, true);
查詢并修改記錄
db.mycollection.findandmodify(query: {condition1: {gte: xx}},
sort: {condition2: -1},
update: {gte: xx}}, sort: {condition2: -1}, update: {set: {target1: 'yy'}, $inc: {target2: 2}}, remove: true});
集合資料查詢
查詢所有記錄
db.mycollection.find();
查詢第一條記錄
db.mycollection.findone();
資料去重
db.mycollection.distinct(“fieldname”);
數值區間查詢
db.mycollection.find({numfield:{$gte:nn}});
字元串查詢
db.mycollection.find({targetfield:/abc/});
指定字段查詢
db.mycollection.find({},{field1:’abc’,field2:nnn});
指定傳回條數查詢
db.mycollection.find().limit(m).skip(n);
排序
db.mycollection.find().sort({targetfield:-1}); //降序
統計記錄數
db.mycollection.find({target: n }).count();
索引操作
建立
db.mycollection.ensureindex({targetfield: 1});
查詢所有索引
db.mycollection.getindexes();
查詢所有索引大小
db.mycollection.totalindexsize();
查詢索引資訊
db.mycollection.reindex({targetfield: 1});
删除指定索引
db.mycollection.dropindex(“targetfield”);
删除所有索引
db.mycollection.dropindexes();
輔助指令
查詢錯誤資訊
db.getpreverror();
清空錯誤資訊
db.reseterror();
各種幫助資訊
help; db.help(); db.mycollection.help(); db.mycollection.find().help(); rs.help();