MongoDB shell常用命令總結

chenfeng發表於2016-07-05
資料庫操作

1.Help檢視
help;

db.help()                    help on db methods
db.mycoll.help()             help on collection methods
sh.help()                    sharding helpers
rs.help()                    replica set helpers
help admin                   administrative help
help connect                 connecting to a db help
help keys                    key shortcuts
help misc                    misc things to know
help mr                      mapreduce


show dbs                     show database names
show collections             show collections in current database
show users                   show users in current database
show profile                 show most recent system.profile entries with time >= 1ms
show logs                    show the accessible logger names
show log [name]              prints out the last segment of log in memory, 'global' is default
use                set current database
db.foo.find()                list objects in collection foo
db.foo.find( { a : 1 } )     list objects in foo where a == 1


2.切換/建立資料庫
use ;
如不存在,會建立新的DB,但show dbs,不會顯示,直到進行一次save操作後,才顯示;  


db.getName();
檢視當前使用的資料庫


3.查詢所有DB
show dbs;


4.刪除當前使用資料庫
db.dropDatabase();
 
5.從指定主機上克隆資料庫
db.cloneDatabase(“127.0.0.1”);
將指定機器上的資料庫的資料克隆到當前資料庫
 
6.從指定的機器上覆制指定資料庫資料到某個資料庫
db.copyDatabase("mydb", "temp", "127.0.0.1");
將本機的mydb的資料複製到temp資料庫中(fromdb, todb, fromhost)
 
7.修復當前資料庫
db.repairDatabase();
 
8.檢視當前使用的資料庫
db.getName();
db;
db和getName方法是一樣的效果,都可以查詢當前使用的資料庫
 
9.顯示當前db狀態
db.stats();
 
10.當前db版本
db.version();
 
11.檢視當前db的連結機器地址
db.getMongo();


12.連線遠端Mongo的指定DB
mongo --host 192.168.0.103 rkhdpaas


13.啟動MongoDB
/home/ingage/platform/mongodb/bin/mongod -dbpath=/home/ingage/platform/mongodb/data -logpath=/home/ingage/platform/mongodb/log


14.資料匯入
./mongoimport --db rkhdpaas --collection customData --file /tmp/dev_custom_data_0922.json  --jsonArray


Collection操作


1.得到當前db的所有集合
db.getCollectionNames();


2.得到當前db的所有集合的索引狀態
db.getCollectionNames();


3.檢視當前db的所有集合
show collections;


4.檢視集合幫助
db.yourColl.help();


 db.customData.find().help() - show DBCursor help
 db.customData.count()
 db.customData.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
 db.customData.convertToCapped(maxBytes) - calls {convertToCapped:'customData', size:maxBytes}} command
 db.customData.dataSize()
 db.customData.distinct( key ) - e.g. db.customData.distinct( 'x' )
 db.customData.drop() drop the collection
 db.customData.dropIndex(index) - e.g. db.customData.dropIndex( "indexName" ) or db.customData.dropIndex( { "indexKey" : 1 } )
 db.customData.dropIndexes()
 db.customData.ensureIndex(keypattern[,options])
 db.customData.explain().help() - show explain help
 db.customData.reIndex()
 db.customData.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
                                               e.g. db.customData.find( {x:77} , {name:1, x:1} )
 db.customData.find(...).count()
 db.customData.find(...).limit(n)
 db.customData.find(...).skip(n)
 db.customData.find(...).sort(...)
 db.customData.findOne([query])
 db.customData.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
 db.customData.getDB() get DB object associated with collection
 db.customData.getPlanCache() get query plan cache associated with collection
 db.customData.getIndexes()
 db.customData.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
 db.customData.insert(obj)
 db.customData.mapReduce( mapFunction , reduceFunction , )
 db.customData.aggregate( [pipeline], ) - performs an aggregation on a collection; returns a cursor
 db.customData.remove(query)
 db.customData.renameCollection( newName , ) renames the collection.
 db.customData.runCommand( name , ) runs a db command with the given name where the first param is the collection name
 db.customData.save(obj)
 db.customData.stats({scale: N, indexDetails: true/false, indexDetailsKey: , indexDetailsName: })
 db.customData.storageSize() - includes free space allocated to this collection
 db.customData.totalIndexSize() - size in bytes of all the indexes
 db.customData.totalSize() - storage allocated for all data and indexes
 db.customData.update(query, object[, upsert_bool, multi_bool]) - instead of two flags, you can pass an object with fields: upsert, multi
 db.customData.validate( ) - SLOW
 db.customData.getShardVersion() - only for use with sharding
 db.customData.getShardDistribution() - prints statistics about data distribution in the cluster
 db.customData.getSplitKeysForChunks( ) - calculates split points over all chunks and returns splitter function
 db.customData.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
 db.customData.setWriteConcern( ) - sets the write concern for writes to the collection
 db.customData.unsetWriteConcern( ) - unsets the write concern for writes to the collection


5.建立新的集合
db.createCollection("yourColl") 


6.檢視當前集合的狀態
db.userInfo.stats();


7.集合重新命名
db.userInfo.renameCollection("users");
將userInfo重新命名為users


8.刪除當前集合
db.userInfo.drop();


9.清空集合所有資料
db.customData.remove({});


10.查詢當前集合的資料條數
db.yourColl.count();
 
11.檢視資料空間大小
db.userInfo.dataSize();


Collection增刪改操作


1.查詢所有記錄
db.userInfo.find();
相當於:select * from userInfo;
預設每頁顯示20條記錄,當顯示不下的情況下,可以用it迭代命令查詢下一頁資料。注意:鍵入it命令不能帶“;”
但是你可以設定每頁顯示資料的大小,用DBQuery.shellBatchSize = 50;這樣每頁就顯示50條記錄了。
 
2.查詢去掉後的當前聚集集合中的某列的重複資料
db.userInfo.distinct("name");
會過濾掉name中的相同資料
相當於:select distict name from userInfo;
 
3.查詢age = 22的記錄
db.userInfo.find({"age": 22});
相當於: select * from userInfo where age = 22;
 
4.查詢age > 22的記錄
db.userInfo.find({age: {$gt: 22}});
相當於:select * from userInfo where age > 22;
 
5.查詢age < 22的記錄
db.userInfo.find({age: {$lt: 22}});
相當於:select * from userInfo where age < 22;
 
6.查詢age >= 25的記錄
db.userInfo.find({age: {$gte: 25}});
相當於:select * from userInfo where age >= 25;
 
7.查詢age <= 25的記錄
db.userInfo.find({age: {$lte: 25}});
 
8.查詢age >= 23 並且 age <= 26
db.userInfo.find({age: {$gte: 23, $lte: 26}});
 
9.查詢name中包含 mongo的資料
db.userInfo.find({name: /mongo/});
//相當於%%
select * from userInfo where name like ‘%mongo%’;
 
10.查詢name中以mongo開頭的
db.userInfo.find({name: /^mongo/});
select * from userInfo where name like ‘mongo%’;
 
11.查詢指定列name.age資料
db.userInfo.find({}, {name: 1, age: 1});
相當於:select name, age from userInfo;
當然name也可以用true或false,當用ture的情況下河name:1效果一樣,如果用false就是排除name,顯示name以外的列資訊。
 
12.查詢指定列name.age資料, age > 25
db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
相當於:select name, age from userInfo where age > 25;
 
13.按照年齡排序
升序:db.userInfo.find().sort({age: 1});
降序:db.userInfo.find().sort({age: -1});
 
14.查詢name = zhangsan, age = 22的資料
db.userInfo.find({name: 'zhangsan', age: 22});
相當於:select * from userInfo where name = ‘zhangsan’ and age = ‘22’;
 
15.查詢前5條資料
db.userInfo.find().limit(5);
相當於:select top 5 * from userInfo;
 
16.查詢10條以後的資料
db.userInfo.find().skip(10);
相當於:select * from userInfo where id not in (
select top 10 * from userInfo
);
 
17.查詢在5-10之間的資料
db.userInfo.find().limit(10).skip(5);
可用於分頁,limit是pageSize,skip是第幾頁*pageSize
 
18.or與 查詢
db.userInfo.find({$or: [{age: 22}, {age: 25}]});
相當於:select * from userInfo where age = 22 or age = 25;
 
19.查詢第一條資料
db.userInfo.findOne();
相當於:select top 1 * from userInfo;
db.userInfo.find().limit(1);
 
20.查詢某個結果集的記錄條數
db.userInfo.find({age: {$gte: 25}}).count();
相當於:select count(*) from userInfo where age >= 20;
 
21.按照某列進行排序
db.userInfo.find({sex: {$exists: true}}).count();
相當於:select count(sex) from userInfo;


22.新增
db.users.save({name: ‘zhangsan’, age: 25, sex: true});
新增的資料的資料列,沒有固定,根據新增的資料為準
 
23.修改
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’;
 
24.刪除
db.users.remove({age: 132});


索引操作


1.建立索引
db.customData.ensureIndex({ "ownerId" : 1},{ "name" : "idx_ownerId" });
db.customData.ensureIndex({ "tenantId" : 1, "entityId" : 1},{ "name" : "idx_tenantId_entityId" });
 
2.查詢當前聚集集合所有索引
db.customData.getIndexes();
 
3.檢視總索引記錄大小
db.customData.totalIndexSize();
 
4.讀取當前集合的所有index資訊
db.customData.reIndex();
 
5.刪除指定索引
db.users.dropIndex("idx_ownerId");
 
6.刪除所有索引索引
db.users.dropIndexes();


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