设为首页 加入收藏

TOP

MongoDB学习(三)MongoDB shell命令行的使用
2014-11-24 08:19:31 来源: 作者: 【 】 浏览:2
Tags:MongoDB 学习 shell 命令 使用

首先要启动MongoDB shell工具,即bin下的mongo.exe
常用shell命令如下:
1、查询本地所有 数据库名称
> show dbs;
2、切换至指定数据库环境(若无指定的数据库,则创建新的库)
> use dbtest;
切换至dbtest库或创建名为dbtest的库
3、查询当前库下的所有聚集集合collection(相当于table)
www.2cto.com
> show collections;
4、创建聚集集合
> db.createCollection('employee');
创建了一个名为'employee'的聚集集合
5、插入数据
> db.employee.insert({'uname':'teddy','age':24,'salary':11000});
往'employee'聚集集合中插上一条数库,name为'teddy',age为'24',salary为'11000'
6、查询聚集集合中数据条数
> db.employee.count();
7、查询age为了23的数据
> db.employee.find({"age":23});
8、查询salary大于5000的数据
www.2cto.com
> db.employee.find({salary:{$gt:5000}});
9、查询age小于23,salary大于8000的数据
> db.employee.find({age:{$lt:24}},{salary:{$gt:8000}});
10、查询salary小于4000或salary大于20000的数据
> db.employee.find({$or: [{salary: {$lt:4000}}, {salary: {$gt:20000}}]});
11、查询指定列的数据
> db.employee.find({},{age:1,salary:1});
1表示显示此列的意思,也可以用true表示
12、查询uname中包含'e'的数据
> db.employee.find({uname:/e/});
13、查询以a打头的数据
> db.employee.find({uname:/^a/});
14、查询age列数据,并去掉重复数据
> db.employee.distinct('age');
15、查询前10条数据
> db.employee.find().limit(10);
16、查询1条以后的所有数据
> db.employee.find().skip(1);
17、查询第一条数据
> db.employee.findOne();
18、查询结果集的记录数(查询salary小于4000或大于10000的记录数)
db.employee.find({$or: [{salary: {$lt:4000}}, {salary: {$gt:10000}}]}).count();
19、按salary升序排序
> db.employee.find().sort({salary:1});
按照salary字段升序排序
20、降序 www.2cto.com
> db.employee.find().sort({salary:-1});
按照salary字段降序排序
21、根据uname修改age
> db.employee.update({uname:'jim'},{$set:{age:22}},false,true);
db.collection.update( criteria, objNew, upsert, multi )
criteria : update的查询条件,类似sql update查询内where后面的
objNew : update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的
upsert : 如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
multi : mongodb默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
22、将指定uname的age字段增加5
> db.employee.update({uname:'jim'},{$inc:{age:5}},false,true);
将uname为‘jim’的age字段加5
23、删除uname为'rose'的数据
> db.employee.remove({uname:'rose'});
24、集合collection重命名 www.2cto.com
> db.employee.renameCollection('t_emp');
将employee集合重命名为't_emp'
25、删除集合
> db.emp_test.drop();
删除名为'emp_test'的集合
26、删除当前数据库
> db.dropDatabase();
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇MongoDB面试题集锦 下一篇记录数据库执行情况来分析数据库..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Redis on AWS:Elast (2025-12-27 04:19:30)
·在 Spring Boot 项目 (2025-12-27 04:19:27)
·使用华为开发者空间 (2025-12-27 04:19:24)
·Getting Started wit (2025-12-27 03:49:24)
·Ubuntu 上最好用的中 (2025-12-27 03:49:20)