mongodb的基本操作

一、mongodb的连接工具

这里可以先安装一个视图化 的工具Robomongo,网上搜索下载即可


这是我的Robomongo,其中create(创建一个链接)


这是create弹出的框,name 自己随意取一个名字,address这个需要填写安装的mongodb电脑或服务器上的地址
如果mongodb添加了权限认证,那么还需要在Authentication添加用户名和密码 和要链接的数据库名
添加好就可以进入了(如果Test中有一些测试不通过,有可能在配合时,启动了--auth 权限认证,去掉后重新启动)

进入后创建数据库,并创建集合


二、介绍mongodb和mongodb的基本操作

Mongodb的介绍:

1.什么是mongodb:
 (1)它存储的数据格式类似(json)的bson格式的数据,最后可以输出为Json格式的数据,这里可以先理解为Json格式,那么这个时候理解起来就容易一些,
Json格式是以键值对的形式存储,同时,还可以在其中存储数据,那么这就相当于在这个集合中再创建一个集合,可以创建很多的集合。
(2)mongodb存储是以文档的形式存储的,并维护一个配置文件,这个配置文件存放的一些我们存储信息的位置信息,这里不需要去关心。

mongodb的基本操作

2.  查看数据库
show dbs;
 
3.  进入到某一数据库下面
use dbname;
 
4.  查看集合
show collections;
 
5.  查看集合所有数据
 db.collectionname.find();
 
6.  查看集合一条数据
db.collectionname.findOne();
 
7.  插入数据到集合
单条 :db.collectionname.insert({"col1":"11"});
多条 :for(var i=1;i<10;i++) db.collectionname.save({x:4,j:i});
 
8.  关闭 mongodb服务
use admin;
db.shutdownServer();
 
9.  带条件查询数据
db.collectionname.find({条件 });
 
10. 修改操作
db.collectionname.update({条件 },{$set:{j:"44"}});
 
11. 删除操作
 db.collectionname.remove({条件 })
 
12. 创建数据库
use dbname; //说明 :需要创建一个集合这个库才创建成功
 
13. 删除数据库
use dbname;
db.dropDatabase();
 
14.   删除集合
db.collectionname.drop();
 
15. 查看复制集状态
rs.status()
16. 查看从库状态
db.printSlaveReplicationInfo()
 
17. 设置从库可查询
db.getMongo().setSlaveOk()
18.   创建索引
db.collectionname.ensureIndex({字段名 :1})
 
19.   查看索引
db.collectionname.getIndexes();
 
20.   删除索引
db.collectionname.dropIndex({字段名 :1})
 
21.   重建索引
db.aa.reIndex();
22. 查看执行计划
db.collectionname.find().explain();

接下来我们结合菜鸟教程中的案例来敲一些命令
1.增
db.  collectionname.insert({'name':'ice'}) (该命令是将这个数据插入到集合中,  collectionname 是自己集合的名称, {'name':'ice'} 这个就是json格式的数据,一定需要符合json格式的数据,不符合是无法插入的 ),每次插入只能插入一条数据
插入文档你也可以使用 db.col.save(document) 命令。如果不指定 _id 字段 save() 方法类似于 insert() 方法。如果指定 _id 字段,则会更新该 _id 的数据
2.查
db.collectionname.find() 该命令是查找该集合中所有数据
db.collectionname.findOne()  该命令是查找该集合中的第一条数据
根据条件查询

如果你熟悉常规的 SQL 数据,通过下表可以更好的理解 MongoDB 的条件语句查询:

操作 格式 范例 RDBMS中的类似语句
等于 {<key>:<value>} db.col.find({"by":"菜鸟教程"}).pretty() where by = '菜鸟教程'
小于 {<key>:{$lt:<value>}}   db.col.find({"likes":{$lt:50}}).pretty()    where likes < 50 
小于或等于 {<key>:{$lte:<value>}} db.col.find({"likes":{$lte:50}}).pretty() where likes <= 50
大于 {<key>:{$gt:<value>}} db.col.find({"likes":{$gt:50}}).pretty() where likes > 50
大于或等于 {<key>:{$gte:<value>}} db.col.find({"likes":{$gte:50}}).pretty() where likes >= 50
不等于 {<key>:{$ne:<value>}} db.col.find({"likes":{$ne:50}}).pretty() where likes != 50
db.collectionname.find({'name':'ice'});根据条件查找,这里相当于 where name = 'ice' 
下面的这些大于等于比较,数据中都一个字段为数字,这样就比较好

接下来,了解一下find中多个{}是如何操作的
第一个{}这个是查询的条件,第二个是查找的指定字段

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);
相当于:selecttop 5 * from userInfo;

16、查询10条以后的数据
db.userInfo.find().skip(10);
相当于:select * from userInfo where id not in (
selecttop 10 * from userInfo
);

17、查询在5-10之间的数据
db.userInfo.find().limit(10).skip(5);

可用于分页,limit是pageSize,skip是第几页*pageSize
18、or与 and 查询
db.userInfo.find({$or: [{age: 22}, {age: 25}]});
相当于:select * from userInfo where age = 22 or age = 25;
db.userinfo.find({$and:[{age:22},{name:ice}]})
相当于:select * from userInfo where age = 22 and name = 'ice';

19、查询第一条数据
db.userInfo.findOne();
相当于:selecttop 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;

索引
1、创建索引
db.userInfo.ensureIndex({name: 1});
db.userInfo.ensureIndex({name: 1, ts: -1});

2、查询当前聚集集合所有索引
db.userInfo.getIndexes();

3、查看总索引记录大小
db.userInfo.totalIndexSize();

4、读取当前集合的所有index信息
db.users.reIndex();

5、删除指定索引
db.users.dropIndex("name_1");

6、删除所有索引索引
db.users.dropIndexes();

修改、添加、删除集合数据
1、添加
db.users.save({name: ‘zhangsan', age: 25, sex: true});

添加的数据的数据列,没有固定,根据添加的数据为准
2、修改
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';

3、删除
db.users.remove({age: 132});

4、查询修改删除
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 
七、语句块操作 
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();

查看聚集集合基本信息
1、查看帮助  db.yourColl.help();
2、查询当前集合的数据条数  db.yourColl.count();
3、查看数据空间大小 db.userInfo.dataSize();
4、得到当前聚集集合所在的db db.userInfo.getDB();
5、得到当前聚集的状态 db.userInfo.stats();
6、得到聚集集合总大小 db.userInfo.totalSize();
7、聚集集合储存空间大小 db.userInfo.storageSize();
8、Shard版本信息  db.userInfo.getShardVersion()
9、聚集集合重命名 db.userInfo.renameCollection("users"); 将userInfo重命名为users
10、删除当前聚集集合 db.userInfo.drop();

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





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值