数据库操作
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();