高明1028筆記﹉MogoDB常用

MongoDB指令

輸入help可以看到基本操作命令:

  • show dbs:顯示數據庫列表
  • show collections:顯示當前數據庫中的集合(類似關系數據庫中的表)
  • show users:顯示用戶
  • use <db name>:切換當前數據庫,這和MS-SQL里面的意思一樣
  • db.help():顯示數據庫操作命令,里面有很多的命令
  • db.foo.help():顯示集合操作命令,同樣有很多的命令,foo指的是當前數據庫下,一個叫foo的集合,并非真正意義上的命令
  • db.foo.find():對于當前數據庫中的foo集合進行數據查找(由于沒有條件,會列出所有數據)
  • db.foo.find( { a : 1 } ):對于當前數據庫中的foo集合進行查找,條件是數據中有一個屬性叫a,且a的值為1
MongoDB沒有創建數據庫的命令,但有類似的命令。

如:如果你想創建一個“myTest”的數據庫,先運行use myTest命令,之后就做一些操作(如:db.createCollection('user')),這樣就可以創建一個名叫“myTest”的數據庫。


數據庫常用命令

  • Help查看命令提示
 help
  db.help();
  db.yourColl.help();
  db.youColl.find().help();
  rs.help();
  • 切換/創建數據庫
 use yourDB;  當創建一個集合(table)的時候會自動創建當前數據庫
  • 查詢所有數據庫
 show dbs;
  • 刪除當前使用數據庫
 db.dropDatabase();
  • 從指定主機上克隆數據庫
 db.cloneDatabase(“127.0.0.1”); 將指定機器上的數據庫的數據克隆到當前數據庫
  • 從指定的機器上復制指定數據庫數據到某個數據庫
 db.copyDatabase("mydb", "temp", "127.0.0.1");將本機的mydb的數據復制到temp數據庫中
  • 修復當前數據庫
 db.repairDatabase();
  • 查看當前使用的數據庫
 db.getName();
 db; db和getName方法是一樣的效果,都可以查詢當前使用的數據庫
  • 顯示當前db狀態
 db.stats();
  • 當前db版本
 db.version();
  • 查看當前db的鏈接機器地址
 db.getMongo();

Collection聚集集合

  • 創建一個聚集集合(table)
 db.createCollection(“collName”, {size: 20, capped: 5, max: 100});
  • 得到指定名稱的聚集集合(table)
 db.getCollection("account");
  • 得到當前db的所有聚集集合
 db.getCollectionNames();
  • 顯示當前db所有聚集索引的狀態
 db.printCollectionStats();

用戶相關

  • 添加一個用戶
 db.addUser("name");
 db.addUser("userName", "pwd123", true); 添加用戶、設置密碼、是否只讀
  • 數據庫認證、安全模式
 db.auth("userName", "123123");
  • 顯示當前所有用戶
 show users;
  • 刪除用戶
 db.removeUser("userName");

其他

  • 查詢之前的錯誤信息
 db.getPrevError();
  • 清除錯誤記錄
 db.resetError();

查看聚集集合基本信息

  • 查看幫助
  db.yourColl.help();
  • 查詢當前集合的數據條數
  db.yourColl.count();
  • 查看數據空間大小
 db.userInfo.dataSize();
  • 得到當前聚集集合所在的db
 db.userInfo.getDB();
  • 得到當前聚集的狀態
 db.userInfo.stats();
  • 得到聚集集合總大小
 db.userInfo.totalSize();
  • 聚集集合儲存空間大小
 db.userInfo.storageSize();
  • Shard版本信息
  db.userInfo.getShardVersion()
  • 聚集集合重命名
 db.userInfo.renameCollection("users"); 將userInfo重命名為users
  • 刪除當前聚集集合
 db.userInfo.drop();

聚集集合查詢

  • 查詢所有記錄
db.userInfo.find();

相當于:select* from userInfo;默認每頁顯示20條記錄,當顯示不下的情況下,可以用it迭代命令查詢下一頁數據。注意:鍵入it命令不能帶“;”
但是你可以設置每頁顯示數據的大小,用DBQuery.shellBatchSize= 50;這樣每頁就顯示50條記錄了。

  • 查詢去掉后的當前聚集集合中的某列的重復數據
db.userInfo.distinct("name");

會過濾掉name中的相同數據
相當于:select distict name from userInfo;

  • 查詢age = 22的記錄
db.userInfo.find({"age": 22});

相當于:select * from userInfo where age = 22;

  • 查詢age > 22的記錄 >用"$gt"表示
db.userInfo.find({age: {$gt: 22}});

相當于:select * from userInfo where age >22;

  • 查詢age < 22的記錄 <用$lt表示
db.userInfo.find({age: {$lt: 22}});

相當于:select * from userInfo where age <22;

  • 查詢age >= 25的記錄 >=用$gte表示
db.userInfo.find({age: {$gte: 25}});

相當于:select * from userInfo where age >= 25;

  • 查詢age <= 25的記錄 <=用$lte表示
db.userInfo.find({age: {$lte: 25}});
  • 查詢age != 25的記錄 !=用$ne表示
db.userInfo.find({age: {$ne: 22}});
  • 查詢age =20 或者 age=25 or用$or表示
db.userInfo.find({$or:[{age: 20},{age: 25}]});
  • 查詢age 在[20,25]中查詢 in用$in表示,與or類似
db.userInfo.find({age:{$in[20,25]}});
  • 查詢age 不在[20,25]中查詢 notin用$nin表示,[]中的值為排除項
db.userInfo.find({age:{$nin[20,25]}});
  • 查詢age >= 23 并且 age <= 26
db.userInfo.find({age: {$gte: 23, $lte: 26}});
  • 查詢name以"t"開頭,以"m"為結尾的數據
db.userInfo.find({name: /"Ctrl"t/,name: /"Ctrl"m/});
  • 查詢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,當用ture的情況下河name:1效果一樣,如果用false就是排除name,顯示name以外的列信息。

  • 查詢指定列name、age數據, age > 25
db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});

相當于:select name, age from userInfo where age >25;

  • 按照年齡排序
    升序:db.userInfo.find().sort({age: 1});
    降序:db.userInfo.find().sort({age: -1});

  • 查詢name = zhangsan, age = 22的數據

db.userInfo.find({name: 'zhangsan', age: 22});

相當于:select * from userInfo where name = ‘zhangsan’ and age = ‘22’;

  • 查詢前5條數據
db.userInfo.find().limit(5);

相當于:selecttop 5 * from userInfo;

  • 查詢10條以后的數據
db.userInfo.find().skip(10);

相當于:select * from userInfo where id not in ( selecttop 10 * from userInfo );

  • 查詢在5-10之間的數據
db.userInfo.find().limit(10).skip(5);

可用于分頁,limit是pageSize,skip是第幾頁*pageSize

  • or與 查詢
db.userInfo.find({$or: [{age: 22}, {age: 25}]});

相當于:select * from userInfo where age = 22 or age = 25;

  • 查詢第一條數據
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 >= 20;

  • 按照某列進行排序
db.userInfo.find({sex: {$exists: true}}).count();

相當于:select count(sex) from userInfo;

索引

  • 創建索引
db.userInfo.ensureIndex({name: 1});
db.userInfo.ensureIndex({name: 1, ts: -1});
  • 查詢當前聚集集合所有索引
db.userInfo.getIndexes();
  • 查看總索引記錄大小
db.userInfo.totalIndexSize();
  • 讀取當前集合的所有index信息
db.users.reIndex();
  • 刪除指定索引
db.users.dropIndex("name_1");
  • 刪除所有索引索引
db.users.dropIndexes();

修改、添加、刪除集合數據

  • 添加
db.users.save({name: ‘zhangsan’, age: 25, sex: true});

添加的數據的數據列,沒有固定,根據添加的數據為準

  • 修改
db.users.update({age: 25}, {$set: {name: 'changeName'}}, false, true);

相當于:update users set name = ‘changeName’ where age = 25;

db.users.update({name: 'Lisi'}, {$inc: {age: 50}}, false, true);

相當于:update users set age = age + 50 where name = ‘Lisi’;

db.users.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'hoho'}}, false, true);

相當于:update users set age = age + 50, name = ‘hoho’ where name = ‘Lisi’;

  • 刪除
db.users.remove({age: 132});
  • 查詢修改刪除
db.users.findAndModify({
    query: {age: {$gte: 25}},
    sort: {age: -1},
    update: {$set: {name: 'a2'}, $inc: {age: 2}},
    remove: true
});
db.runCommand({ findandmodify : "users",
    query: {age: {$gte: 25}},
    sort: {age: -1},
    update: {$set: {name: 'a2'}, $inc: {age: 2}},
    remove: true
});
update 或 remove 其中一個是必須的參數; 其他參數可選。
參數 詳解 默認值
query 查詢過濾條件 {}
sort 如果多個文檔符合查詢過濾條件,將以該參數指定的排列方式選擇出排在首位的對象,該對象將被操作 {}
remove 若為true,被選中對象將在返回前被刪除 N/A
update 一個 修改器對象 N/A
new 若為true,將返回修改后的對象而不是原始對象。在刪除操作中,該參數被忽略。 false
fields 參見Retrieving a Subset of Fields (1.5.0+) All fields
upsert 創建新對象若查詢結果為空。 示例 (1.5.4+) false

語句塊操作

  • 簡單Hello World
print("Hello World!");

這種寫法調用了print函數,和直接寫入"Hello World!"的效果是一樣的;

  • 將一個對象轉換成json
tojson(new Object());
tojson(new Object('a'));
  • 循環添加數據
> for (var i = 0; i < 30; i++) {
... db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
... };

這樣就循環添加了30條數據,同樣也可以省略括號的寫法

> for (var i = 0; i < 30; i++) db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});

也是可以的,當你用db.users.find()查詢的時候,顯示多條數據而無法一頁顯示的情況下,可以用it查看下一頁的信息;

  • find 游標查詢
>var cursor = db.users.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.users.find().toArray();
> printjson(arr[2]);

用toArray方法將其轉換為數組

  • 定制我們自己的查詢結果
    只顯示age <= 28的并且只顯示age這列數據
db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);
db.users.find({age: {$lte: 28}}, {age: true}).forEach(printjson);

排除age的列

db.users.find({age: {$lte: 28}}, {age: false}).forEach(printjson);
  • forEach傳遞函數顯示信息
db.things.find({x:4}).forEach(function(x) {print(tojson(x));});
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容