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}})
    });

猜你喜欢

转载自blog.csdn.net/liuzishang/article/details/83538826