1. 程式人生 > >mongodb shell常用命令,同樣適合於NoSqlL Manager for Mongodb 中shell

mongodb shell常用命令,同樣適合於NoSqlL Manager for Mongodb 中shell

db.Eggs.find({Img:/115.28.183.79:8899/}).forEach(function(item){ 
    db.Eggs.update({_id:item._id},{$set:{'Img':item.Img.replace("115.28.183.79:8899","api.zhukeshengtai.com")}})
    });
db.Eggs.find({},{Img:1})
一、常用命令
1、Help檢視命令提示
help 
db.help();
db.Collectionname.help();  --your collection name,you can see the following functions
   db.collectionname.find().help() - show DBCursor help
    db.collectionname.count()
    db.collectionname.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
    db.collectionname.convertToCapped(maxBytes) - calls {convertToCapped:'" + shortName + "', size:maxBytes}} command
    db.collectionname.dataSize()
    db.collectionname.distinct( key ) - e.g. db." + shortName + ".distinct( 'x' )
    db.collectionname.drop() drop the collection
    db.collectionname.dropIndex(index) - e.g. db." + shortName + ".dropIndex( \"indexName\" ) or db." + shortName + ".dropIndex( { \"indexKey\" : 1 } )
    db.collectionname.dropIndexes()
    db.collectionname.ensureIndex(keypattern[,options])
    db.collectionname.explain().help() - show explain help
    db.collectionname.reIndex()
    db.collectionname.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
                                               e.g. db." + shortName + ".find( {x:77} , {name:1, x:1} )
    db.collectionname.find(...).count()
    db.collectionname.find(...).limit(n)
    db.collectionname.find(...).skip(n)
    db.collectionname.find(...).sort(...)
    db.collectionname.findOne([query])
    db.collectionname.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
    db.collectionname.getDB() get DB object associated with collection
    db.collectionname.getPlanCache() get query plan cache associated with collection
    db.collectionname.getIndexes()
    db.collectionname.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
  
    db.collectionname.insert(obj)
    db.collectionname.mapReduce( mapFunction , reduceFunction , <optional params> )
    db.collectionname.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor
    db.collectionname.remove(query)
    db.collectionname.renameCollection( newName , <dropTarget> ) renames the collection.
    db.collectionname.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
    db.collectionname.save(obj)
    db.collectionname.stats({scale: N, indexDetails: true/false, " +
          "indexDetailsKey: <index key>, indexDetailsName: <index name>})
  
    db.collectionname.storageSize() - includes free space allocated to this collection
    db.collectionname.totalIndexSize() - size in bytes of all the indexes
    db.collectionname.totalSize() - storage allocated for all data and indexes
    db.collectionname.update(query, object[, upsert_bool, multi_bool]) - instead of two flags, you can pass an object with fields: upsert, multi
    db.collectionname.validate( <full> ) - SLOW;
    
    db.collectionname.getShardDistribution() - prints statistics about data distribution in the cluster
    db.collectionname.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function
    db.collectionname.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
    db.collectionname.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection
    db.collectionname.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection
    return __magicNoPrint;
db.youColl.find().help();
rs.help()
help 
db.help();
db.yourColl.help();
db.youColl.find().help();
rs.help()
2、切換/建立資料庫
use yourDB; 當建立一個集合(table)的時候會自動建立當前資料庫
3、查詢所有資料庫
show dbs;
4、刪除當前使用資料庫
db.dropDatabase();?
5、從指定主機上克隆資料庫
db.cloneDatabase(“127.0.0.1”);
6、從指定的機器上覆制指定資料庫資料到某個資料庫
db.copyDatabase("mydb", "temp", "127.0.0.1");
將本機的mydb的資料複製到temp資料庫中
7、修復當前資料庫
db.repairDatabase();
8、檢視當前使用的資料庫
db.getName();
db; db和getName方法是一樣的效果,都可以查詢當前使用的資料庫
9、顯示當前db狀態
db.stats();
10、當前db版本
db.version();
11、檢視當前db的連結機器地址
db.getMongo();
二、Collection(table)聚集集合
1、建立一個聚集集合(table)
db.createCollection(“collName”, {size: 20, capped: 5, max: 100});//建立成功會顯示{“ok”:1}
2、得到指定名稱的聚集集合(table)
db.getCollection("account");
3、得到當前db的所有聚集集合
db.getCollectionNames();
4、顯示當前db所有聚集索引的狀態
db.printCollectionStats();
三、使用者相關
1、新增一個使用者
db.addUser("name");
 
db.addUser("userName", "pwd123", true); 
新增使用者、設定密碼、是否只讀
2、顯示當前所有使用者
show users;
3、刪除使用者
db.removeUser("userName");
以上都是一些最基本的命令,我就當做筆記來看了。更加深入的crud我都還沒有嘗試,等我嘗試過了再寫。
語句塊操作
1、簡單Hello World
print("Hello World!");
這種寫法呼叫了print函式,和直接寫入"Hello World!"的效果是一樣的;
2、將一個物件轉換成json
tojson(new Object());
 
tojson(new Object('a'));
3、迴圈新增資料
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檢視下一頁的資訊;
4、find 遊標查詢
var cursor = db.users.find();
 
while (cursor.hasNext()) {
 
printjson(cursor.next());
 
}
這樣就查詢所有的users資訊,同樣可以這樣寫
var cursor = db.users.find();
while (cursor.hasNext()) { printjson(cursor.next); }
同樣可以省略{}號
5、forEach迭代迴圈
db.users.find().forEach(printjson);
forEach中必須傳遞一個函式來處理每條迭代的資料資訊
6、將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]);
7、將find遊標轉換成陣列
var arr = db.users.find().toArray();
 
printjson(arr[2]);
用toArray方法將其轉換為陣列
8、定製我們自己的查詢結果
只顯示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);
9、forEach傳遞函式顯示資訊
db.things.find({x:4}).forEach(function(x) {print(tojson(x));});
其他
1、查詢之前的錯誤資訊
db.getPrevError();
2、清除錯誤記錄
db.resetError();
3、顯示資料庫列表
show dbs
4、顯示當前資料庫中的集合(類似關係資料庫中的表)
show collections
5、顯示使用者
show users


刪除某一欄位
db.Disclose.update({},{$unset:{"context":""}},false,true)

修改Mongodb資料型別
如下命令是將User表中的Name欄位從整型轉換到字串型:
db.User.find({'Name' : { $type : 16 }}).forEach(function(x) {x.Name = String(x.Name);db.User.save(x); }) 
db.table_name.find({modifedDate:{$type:9}}).forEach(function(x){x.modifiedDate=NumberLong(x.modifiedDate.getTime()/1000);db.table_name.save(x)})
其中:type=
Double:1,
String:2,
Object:3,
Array:4,
Binary data:5,
Undefined(deprecated):6,
Onject id:7,
Boolean:8,
Date:9,
Null:10,
Regular Expresion:11,
JavaScript:13,
Symbol:14,
JavaScript(with scope):15,
32-bit integer:16,
Timestamp:17,
64-bit integet:18,
Min key:255,
Max key:127

db.Video.find({'isdelete' : { $type : 1 }}).forEach(function(x){x.isdelete = Int32(x.isdelete);db.Video.save(x); }) 
db.Video.find({"isdelete":0})
db.Video.find({"isdelete":0}).forEach(function(item){ 
    db.Video.update({_id:item._id},{$set:{'isdelete':2}})
    });

db.Video.find({isdelete:{$ne:2}}).forEach(function(item){
    db.Video.update({_id:item._id},{$set:{'isdelete':2}})
    });