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"})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章