Mongo命令行操作查询语法

目录

一、查询

1、查询所有的结果:

2、指定返回那些列(键)

3、where条件

4、使用and 

5、使用or 

6、<, <=, >, >= , != ($lt, $lte, $gt, $gte,$ne ) 

7、使用in, not in ($in, $nin) 

8、匹配null 

9、like (mongoDB 支持正则表达式) 

10、使用distinct 

11、使用count 

12、数组查询 (mongoDB自己特有的) 

12.强大的$where查询

13、取模运算$mod

14、$all

15、$exists 

16、正则表达式

17、$elemMatch

18、查询嵌入对象的值

19、元操作符 $not 取反

20、分页排序查询,倒序(-1),正序(1)

21、分组查询,统计type类型的age总和

二、更新

1、update()命令

2、save()命令 

3、$set

4、增加索引,倒序(-1),正序(1)

三、插入

 1、使用insert或save方法想目标集合插入一个文档:

  2、使用batchInsert方法实现批量插入,它与insert方法非常类似,只是它接受的是一个文档数组作为参数。

四、删除

1、整个表删除

2、删除某些条件的数据,删除type类型是test的数据



一、查询

1、查询所有的结果:

mysql: select * from users;

mongo: db.users.find();

2、指定返回那些列(键)

mysql: select name, skills from users;

mongo: db.users.find({}, {'name' : 1, 'skills' : 1}); 

补充说明: 第一个{} 放where条件 第二个{} 指定那些列显示和不显示 (0表示不显示 1表示显示)

3、where条件

mysql: select name, age, skills from users where name = 'hurry'; 

MongoDB:db.users.find({'name' : 'hurry'},{'name' : 1, 'age' : 1, 'skills' : 1});

4、使用and 

MySQL:select name, age, skills from users where name = 'hurry' and age = 18; 

MongoDB:db.users.find({'name' : 'hurry', 'age' : 18},{'name' : 1, 'age' : 1, 'skills' : 1});

5、使用or 

MySQL:select name, age, skills from users where name = 'hurry' or age = 18; 

MongoDB:db.users.find({ '$or' : [{'name' : 'hurry'}, {'age' : 18}] },{'name' : 1, 'age' : 1, 'skills' : 1});

6、<, <=, >, >= , != ($lt, $lte, $gt, $gte,$ne ) 

MySQL:select * from users where age >= 20 and age <= 30; 

MongoDB:db.users.find({'age' : {'$gte' : 20, '$lte' : 30}});

7、使用in, not in ($in, $nin) 

MySQL:select * from users where age in (10, 22, 26); 

MongoDB:db.users.find({'age' : {'$in' : [10, 22, 26]}});

8、匹配null 

MySQL:select * from users where age is null; 

MongoDB:db.users.find({'age' : null);

9、like (mongoDB 支持正则表达式) 

MySQL:select * from users where name like "%hurry%"; 

MongoDB:db.users.find({name:/hurry/}); 

 

MySQL:select * from users where name like "hurry%"; 

MongoDB:db.users.find({name:/^hurry/}); 

 

10、使用distinct 

MySQL:select distinct (name) from users; 

MongoDB:db.users.distinct('name');

 

11、使用count 

MySQL:select count(*) from users; 

MongoDB:db.users.count(); 

MySQL:select count(*) from logs where createTime >= "2020-06-22 10:00:00" and createTime <= "2020-06-22 22:00:00"

MongoDB:db.getCollection('logs').find
({ "createTime":{"$gte":ISODate("2020-06-22T02:00:00Z"),"$lte":ISODate("2020-06-22T14:00:00Z")}    
}).count();

 

12、数组查询 (mongoDB自己特有的) 

如果skills是 ['java','python'] 

db.users.find({'skills' : 'java'}); 该语句可以匹配成功

$all 

db.users.find({'skills' : {'$all' : ['java','python']}}) skills中必须同时包含java 和 python

$size 

db.users.find({'skills' : {'$size' : 2}}) 遗憾的是$size不能与$lt等组合使用

$slice 

db.users.find({'skills' : {'$slice : [1,1]}}) 

两个参数分别是偏移量和返回的数量

12.强大的$where查询

db.foo.find();                   

{ "_id" : ObjectId("4e17ce0ac39f1afe0ba78ce4"), "a" : 1, "b" : 3, "c" : 10 }

{ "_id" : ObjectId("4e17ce13c39f1afe0ba78ce5"), "a" : 1, "b" : 6, "c" : 6 } 

如果要查询 b = c 的文档怎么办? 

> db.foo.find({"$where":function(){

    for(var current in this){

        for(var other in this){

            if(current != other && this[current] == this[other]){

                return true;    

            }

        }

    }

    return false; 

}}); 

 

{ "_id" : ObjectId("4e17ce13c39f1afe0ba78ce5"), "a" : 1, "b" : 6, "c" : 6 }

13、取模运算$mod

如下面的运算:

db.things.find( "this.a % 10 == 1") 

可用$mod代替:

db.things.find( { a : { $mod : [ 10 , 1 ] } } )

14、$all

$all和$in类似,但是他需要匹配条件内所有的值:

如有一个对象:

{ a: [ 1, 2, 3 ] } 

下面这个条件是可以匹配的: 

db.things.find( { a: { $all: [ 2, 3 ] } } ); 

但是下面这个条件就不行了: 

db.things.find( { a: { $all: [ 2, 3, 4 ] } } );

15、$exists 

$exists用来判断一个元素是否存在: 

如: 

db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回

db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回

16、正则表达式

mongo支持正则表达式,如:

db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写

17、$elemMatch

如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:

> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) 

{ "_id" : ObjectId("4b5783300334000000000aa9"), 

"x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]

$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。 

注意,上面的语句和下面是不一样的。 

> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } ) 

$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }

18、查询嵌入对象的值

db.postings.find( { "author.name" : "joe" } ); 

注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation 

举个例子: 

> db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}}) 

如果我们要查询 authors name 是Jane的, 我们可以这样: 

> db.blog.findOne({"author.name" : "Jane"}) 

如果不用点,那就需要用下面这句才能匹配: 

db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}}) 

下面这句: 

db.blog.findOne({"author" : {"name" : "Jane"}}) 

是不能匹配的,因为mongodb对于子对象,他是精确匹配。

19、元操作符 $not 取反

如: 

db.customers.find( { name : { $not : /acme.*corp/i } } ); 

db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } ); 

mongodb还有很多函数可以用,如排序,统计等,请参考原文。 

mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接: 

http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions

20、分页排序查询,倒序(-1),正序(1)

db.collection.find({“type”:“test”}).sort({“addTime”:-1}).skip(0).limit(2);

21、分组查询,统计type类型的age总和

db.collection.aggregate([{$group:{_id:"$type",total:{$sum:"$age"}}}]);
db.collection.aggregate([{$match:{"name":{$ne:null}}},{$group:{_id:"$type",total:{$sum:"$age"}}}]);

二、更新

mongodb更新有两个命令:

1、update()命令

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,就把按条件查出来多条记录全部更新。 

例:

db.test0.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } ); 只更新了第一条记录

db.test0.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true ); 全更新了

db.test0.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false ); 只加进去了第一条

db.test0.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true ); 全加进去了

db.test0.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} },false,true );全更新了

db.test0.update( { "count" : { $gt : 10 } } , { $inc : { "count" : 1} },false,false );只更新了第一条

 

2、save()命令 

db.collection.save( x ) 

x就是要更新的对象,只能是单条记录。 

如果在collection内已经存在一个和x对象相同的"_id"的记录。mongodb就会把x对象替换collection内已经存在的记录,否则将会插入x对象,如果x内没有_id,系统会自动生成一个再插入。相当于上面update语句的upsert=true,multi=false的情况。

例:

db.test0.save({count:40,test1:"OK"}); #_id系统会生成

db.test0.save({_id:40,count:40,test1:"OK"}); #如果test0内有_id等于40的,会替换,否则插入。

3、$set

用法:{ $set : { field : value } }

就是相当于sql的set field = value,全部数据类型都支持$set。例:

> db.test0.update( { "_id" : 15 } , { $set : { "test1" : "testv1","test2" : "testv2","test3" : "testv3","test4" : "testv4" } } );

 

4、增加索引,倒序(-1),正序(1)

db.collection.ensureIndex({type:1})

5、创建数据库

use logstores //创建数据库

db.createCollection("logs") //创建数据库

sh.shardCollection("logstor.logs", { "id": "hashed" } ) //创建分片键

db.comparelogs.createIndex({"app" : 1,"key" : 1}) //创建联合索引

db.comparelogs.createIndex({createTime : 1}) //创建普通索引

db.comparelogs.createIndex({id: 1},{unique: true}) //创建唯一索引

三、插入

 1、使用insert或save方法想目标集合插入一个文档:

    db.persons.insert({"name":"ryan","age":30});

  2、使用batchInsert方法实现批量插入,它与insert方法非常类似,只是它接受的是一个文档数组作为参数。

    一次发送数十,数百乃至数千个文档会明显提高插入的速度。

    db.persons.batchInsert([{"name":"ryan","age":30},{"name":"pitaya","age":2}]);

四、删除

1、整个表删除

db.collection.drop()

2、删除某些条件的数据,删除type类型是test的数据

db.collection.remove({"type" : "test"})
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值