mongoDB基本語法

BIUBIU發表於2017-10-27

**MongoDB基本語法——資料庫操作**
db:檢視當前指向的資料庫
show dbs:檢視當前所有的資料庫
use 切換到當前資料庫
db.dropDatabase():刪除當前指向的資料庫

**MongoDB基本語法——集合操作*
show collections:檢視當前資料庫所有集合
db.createCollection( [ options]):建立一個集合
db.<集合名稱>.drop():刪除指定的集合

############增刪改#############
增加
db.hero.insert({鍵值對})
db.hero.insert({"_id" : 1})

修改
db.hero.update({name:"swk"},{$set:{name:"bajie"}})
db.hero.update({tiaojian},{$set:{ }},{multi:true})
multi:true 表示修改所有 // 預設false 表示修改符合條件第一條

刪除
db.hero.remove({ }) #刪除所有
db.hero.remove({ },{justOne:true}) #只刪除一條

儲存
db.hero.save({ })
save 相當於update insert

##############查詢#############
1.基本查詢
db.hero.find()
findOne([{文件條件}]):查詢第一個

db.hero.find()pretty()
pretty():將查詢結果格式化展示

2.比較運算子(關係運算子)$lt $lte $gt $gte
$lt :little ~小於 < #less than

$lte :little or equals ~小於等於 <=

$gt :granter ~大於 >

$gte :granter or equals ~大於等於 >=

db.hero.find({age : {$gt : 18}})
db.hero.find({age : {$lte : 16}})

3.邏輯運算子 $or
db.hero.find({$or : [{},{},{},{}] })
db.hero.find({$or : [{name:"sunquan"},{age:{$lte:16}}] })
db.hero.find({$or : [{age:{$gt:20}},{age:{$lt:40}}] }) #年齡大於20小於40
db.hero.find({$or : [{age:{$gt:20}},{age:{$lt:40}}] },sex:"nan") #並且是男的

4.範圍運算子

$in:判斷指定條件是否包含在某個範圍內

db.hero.find( {age : {$in : [20,30,40]} } )
$nin:判斷指定條件是否不包含在某個範圍內

5.正則條件

#從一個字串中匹配一個結果
/reg/:普通正規表示式

db.hero.find({ http : /^www/ }) #表示匹配一條http以www開頭的資料
db.hero.find({ name : /^zhang/}) #表示name以zhang開頭
db.hero.find({ http : /com$/ }) #表示http以com結尾

$regex:指定正規表示式複製程式碼

db.hero.find({ name : {$regex : "^lee"} })
db.hero.find({ name : {$regex : "."} }) # .任意匹配

6.自定義條件

$where:通過函式自定義條件[JS函式]

指定函式中,返回boolean型別的值

this表示每個要查詢的文件

db.hero.find({where : function() {return this.name=="songjia"}})
db.hero.find({where : function() {return this.age > 30}})

7.資料查詢——限制查詢條數
db.hero.find(2) #查詢前兩條
db.hero.find().skip(2) #跳過兩條
db.hero.find().skip(0).limit(10) #從頭查詢十條內容
db.hero.find().skip(10).limit(10) #跳過十條再查詢十條

8.資料查詢——統計
db.hero.count() #統計總共條數
db.hero.count({條件}) #統計符合條件的資料條數

db.hero.find().count()
db.hero.find({條件}).count() #同上述一樣

9.資料查詢——投影:查詢制定的域
find({},{投影欄位:1/0}) #1顯示 0不顯示

db.hero.find({},{name:1})
得到結果
{ "_id" : 24, "name" : "linchong"}
{ "_id" : 25, "name" : "luzhishen"}
{ "_id" : 26, "name" : "huarong"}

db.hero.find({},{name:1 ,_id:0})
得到結果
{"name" : "linchong"}
{"name" : "luzhishen"}
{"name" : "huarong"}

10.資料查詢——排序(1/-1)
db.hero.find().sort({}) #預設升序
db.hero.find().sort({條件})
db.hero.find().sort({name:1},{age:1})
db.hero.find().sort({name:-1}) #降序

11.資料查詢——去重distinct
db.hero.distinct("去重域名稱",{條件}}

db.hero.distinct("age",{}}

得到結果
[21,22,23,24,25]