MongoDB 常用Shell命令

来源:互联网 发布:mac中解压软件 编辑:程序博客网 时间:2024/05/08 08:29
1.查询本地所有数据库名称
>show dbs;

2.切换至指定数据库环境(若无指定的数据库,则创建新的库)
>use mydb;

3.查询当前库下的所有聚集集合collection
>show collections;

4.创建聚集集合
>db.createCollection('mycollection');

5.查询聚集集合中数据条数
>db.mycollection.count();

6.插入数据
>db.mycollection.insert({'username':'xyz_lmn','age':26,'salary':120});

7.查询age等于26的数据
>db.mycollection.find({'age':26});

8.查询salary大于100的数据
>db.mycollection.find({salary:{$gt:100}});

9.查询age小于30,salary大于100的数据
>db.mycollection.find({age:{$lt:30}, salary:{$gt:100}});

10.查询salary小于40或salary大于200的数据
>db.mycollection.find({$or:[{salary:{$lt:40}}, {salary:{$gt:200}}]});

11.查询指定列的数据(_id列是默认显示的)
>db.mycollection.find({},{_id:false, uid:true});

12.查询username中包含'e'的数据
>db.mycollection.find({username:/e/});

13.查询以a打头的数据
>db.mycollection.find({username:/^a/});

14.查询age列数据,并去掉重复数据
>db.mycollection.distinct('age');

15.查询前10条数据
>db.mycollection.find().limit(10);

16.查询1条以后的所有数据
>db.mycollection.find().skip(1);

17.查询第一条记录
>db.mycollection.findOne();

18.查询结果集的记录数(查询salary小于40或大于100的记录数)
>db.mycollection.find({$or:[{salary:{$lt:40}},{salary:{$gt:100}}]}).count();

19.按salary升序排序
>db.mycollection.find().sort({salary:1});

20.按salary降序排序
>db.mycollection.find().sort({salary:-1});

21.根据username修改age
>db.employee.update({username:'jim'},{$set:{age:22}},false,true);
db.collection.update(criteria,objNew,upsert,multi)
critria:update的查询条件,类似sql update查询内where后面的
objNew:update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的
upsert:如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
multi:mongoDB默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。

22.将指定username的age字段增加5
>db.mycollection.update({username:'jim'},{$inc:{age:5}},false,true);

23.删除username为rose的数据
db.mycollection.remove({username:'rose'});
db.mycollection.remove();//删除mycollection中的所有数据

24.集合mycollection重命名
db.mycollection.renameCollection('c_temp');

25.删除集合
>db.c_temp.drop();

26.删除当前数据库
>db.dropDatabase();

27.按时间查询
>stime = new Date()
ISODate("2011-09-05T13:57:21.812Z")
>db.news.find({"time":{"$lt":stime}})
0 0
原创粉丝点击