//創(chuàng)建用戶名密碼
use admin
db.createUser(
{
user: "mongo",
pwd: "7f27cd7ae184274e2ca645f09183fc63",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
use dbName
db.collectionName.find / db.getCollection('collectionName').find
db.foo.update 查看update源碼
對(duì)象{} 數(shù)組[]
一條數(shù)據(jù)是一個(gè)文檔 多個(gè)文檔是一個(gè)集合
bson:二進(jìn)制json
將json轉(zhuǎn)為bson存入數(shù)據(jù)庫 bson大于4MB無法存入 V1.8:16MB
計(jì)算json轉(zhuǎn)為bson大小 Object.bsonsize(doc)
與mysql中的字段對(duì)比說明
$project
# 返回哪些字段,select,說它像select其實(shí)是不太準(zhǔn)確的,因?yàn)閍ggregate是一個(gè)階段性管道操作符,$project是取出哪些數(shù)據(jù)進(jìn)入下一個(gè)階段管道操作,真正的最終數(shù)據(jù)返回還是在group等操作中;
$match
# 放在group前相當(dāng)于where使用,放在group后面相當(dāng)于having使用
$sort
# 排序1升-1降 sort一般放在group后,也就是說得到結(jié)果后再排序,如果先排序再分組沒什么意義;
$limit
# 相當(dāng)于limit m,不能設(shè)置偏移量
$skip
# 跳過第幾個(gè)文檔
$unwind
# 把文檔中的數(shù)組元素打開,并形成多個(gè)文檔,參考Example1
$group: { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, ...
# 按什么字段分組,注意所有字段名前面都要加的是普通常量,其中accumulator又包括以下幾個(gè)操作符
$sum
,$avg
,$first
,$last
,$max
,$min
,$push
,$addToSet
如果group by null就是 count(*)的效果
$geoNear # 取某一點(diǎn)的最近或最遠(yuǎn),在LBS地理位置中有用
$out # 把結(jié)果寫進(jìn)新的集合中云茸。注意1,不能寫進(jìn)一個(gè)分片集合中。注意2,不能寫進(jìn)
db.getCollection('user').aggregate(
[
{$project:
{phone:{$substr:['$phone', 0, 7]}}
},
{$group:
{'_id':'$phone','count':{$sum:1}}
}
]
)
更新:
//更新一條
db.sang_collect.update({x:1},{x:99})
//更新多條
db.collection.update({x:1},{$set:{x:99}},false,true)
第一個(gè)false表示如果不存在update記錄鸠项,是否將我們要更新的文檔作為一個(gè)新文檔插入做粤,true表示插入贴唇,false表示不插入喷众,默認(rèn)為false浓恶,第二個(gè)true表示是否更新全部查到的文檔,false表示只更新第一條記錄岭参,true表示更新所有查到的文檔。
//如果字段不存在則創(chuàng)建
db.collection.update({x:1},{$set:{x:99}})
//刪除字段
db.collection.update({x:1},{$unset:{x:99}})
//修改內(nèi)嵌文檔
db.collection.update({name:"三國(guó)演義"},{$set:{"author.name":"明代羅貫中"}})
//inc只能用來操作數(shù)字演侯,不能用來操作null、布爾等背亥。
db.collection.update({name:"三國(guó)演義"},{$inc:{"author.age":1}})
//$push可以向已有數(shù)組末尾追加元素秒际,要是不存在就創(chuàng)建一個(gè)數(shù)組
db.collection.update({name:"三國(guó)演義"},{$push:{comments:"好書666"}})
//如果想一次添加多條評(píng)論,可以結(jié)合push:{comments:{$each:["111","222","333"]}}})
//使用$slice來固定數(shù)組的長(zhǎng)度 超出長(zhǎng)度保留最新
db.collection.update({name:"三國(guó)演義"},{$push:{comments:{$each:["444","555"],$slice:5}}})
//使用$sort對(duì)數(shù)據(jù)先進(jìn)行排序 執(zhí)行順序-1表示降序狡汉,1表示升序娄徊。 sort/slice
db.collection.update({class:"三年級(jí)二班"},{$push:{students:{$each:[{name:"張一百",score:100},{name:"張九九",score:99},{name:"張九八",score:98}],$slice:5,$sort:{score:-1}}}})
db.collection.update({'name':'三國(guó)演義'},{$push:{'comments':{$each:[1,2,3],$slice:5,$sort:1}}})
//表示要插入的值如果存在則不插入,否則插入 無法和sort和slice配合使用
db.getCollection('runoob').update({'name':'三國(guó)演義'},{$addToSet:{'comments':1}})
db.getCollection('runoob').update({'name':'三國(guó)演義'},{$addToSet:{'comments':{$each:[19,2,3]}}})
//$pop可以用來刪除數(shù)組中的數(shù)據(jù) 1表示從comments數(shù)組的末尾刪除一條數(shù)據(jù)盾戴,-1表示從comments數(shù)組的開頭刪除一條數(shù)據(jù)寄锐。
db.sang_collect.update({name:"三國(guó)演義"},{$pop:{comments:1}})
//使用$pull我們可以按條件刪除數(shù)組中的某個(gè)元素
db.getCollection('runoob').update({'name':'三國(guó)演義'},{$pull:{students:{score:100}}})
db.getCollection('runoob').update({'name':'三國(guó)演義'},{$pull:{comments:1}})
//通過下標(biāo)修改
db.getCollection('runoob').update({'name':'三國(guó)演義'},{$set:{'comments.0':22}})
db.getCollection('runoob').update({'name':'三國(guó)演義'},{$set:{'students.0.score':22}})
//不知道我要修改的數(shù)據(jù)處于數(shù)組中的什么位置,這個(gè)時(shí)候可以使用$符號(hào)來解決
db.getCollection('runoob').update({'students.score':22},{$set:{'students.$.score':33}})
db.getCollection('runoob').update({'comments':3},{$set:{'comments.$':33}})
//save是shell中的一個(gè)函數(shù)尖啡,接收一個(gè)參數(shù)橄仆,這個(gè)參數(shù)就是文檔,如果文檔中有_id參數(shù)save會(huì)執(zhí)行更新操作衅斩,否則執(zhí)行插入操作
db.sang_collect.save({x:111})
查詢
//查詢
db.sang_collect.find({x:1})
//查詢 and
db.sang_collect.find({x:1,y:2})
//自定義返回字段 1表示返回 0表示不返回 _id默認(rèn)返回
db.sang_collect.find({x:1},{x:1,_id:0})
//比較運(yùn)算符
符號(hào) | 含義 |
---|---|
$lt | < |
$lte | <= |
$gt | > |
$gte | >= |
$ne | != |
//比較運(yùn)算符用法
db.sang_collect.find({key:{$ne:value}})
// 查詢?cè)谀硞€(gè)集合里 $in
db.collection.find({key:{$in:[value1,value2,……]}})
//$nin
查詢不在某個(gè)集合
db.collection.find({key:{$nin:[value1,value2,……]}})
//$or
查詢或
db.collection.find({key:{$or:[{key1:value1},{key2:value2},……]}})
//$type
根據(jù)數(shù)據(jù)類型查找
db.collection.find({key:{$type:1}})
//1表示數(shù)字盆顾,其他數(shù)據(jù)類型對(duì)應(yīng)的數(shù)字參見下表。
類型 | 對(duì)應(yīng)數(shù)字 | 別名 | 說明 |
---|---|---|---|
Double1 | 1 | double | |
String | 2 | string | |
Object | 3 | object | |
Array | 4 | array | |
Binary data | 5 | binData | |
Undefined | 6 | undefined 棄用 | |
ObjectId | 7 | objectId | |
Boolean | 8 | bool | |
Date | 9 | date | |
Null | 10 | null | |
Regular Expression | 11 | regex | |
DBPointer | 12 | dbPointer | |
JavaScript | 13 | javascript | |
Symbol | 14 | symbol | |
JavaScript(with scope) | 15 | javascriptWithScope | |
32-bit integer | 16 | int | |
Timestamp | 17 | timestamp | |
64-bit integer | 18 | long | |
Min key | -1 | minKey | |
Max key | 127 | maxKey |
//$not
可以配合表達(dá)式查詢 $type/$lte……
db.collection.find({key:{$not:{$gte:2}}})
//$and
db.collection.find({$and:[{key:{$gte:value}},{key:{$lte:value}}]})
//null 查詢某個(gè)字段為null的文檔
db.collection.find({key:null}) //會(huì)查詢出字段不存在的數(shù)據(jù)
db.collection.find({key:{$in:[null], $exists:true}})
//正則查詢
db.collection.find({key://})
//數(shù)組查詢
{
"_id" : ObjectId("59f208bc7b00f982986c669c"),
"x" : [
5.0,
25.0
]
}
db.collection.find({key:value}) //包含一個(gè)
db.collection.find{(key:{$all:[value1,value2……]}}) //包含多個(gè)
db.collection.find({key:[value1,value2……]}) //精確匹配
db.collection.find({key.2:value}) //根據(jù)下標(biāo)精確匹配
db.collection.find({key:{$size:2}}) //數(shù)組長(zhǎng)度匹配
db.collection.find({},{key:{$slice:2}}) //展示數(shù)組中前兩條數(shù)據(jù) 正數(shù):從前定位 負(fù)數(shù):從后低定位
db.collection.find({},{key:{$slice:[1,3]}}) //展示數(shù)組區(qū)間 2-4
//$elemMatch
同時(shí)使用查詢條件中的兩個(gè)語句與一個(gè)數(shù)組元素進(jìn)行比較畏梆。
db.collection.find({key:{$elemMatch:{$lt:value,$gt:vale}}})
//嵌套文檔查詢
{
"_id" : ObjectId("59f20c9b7b00f982986c669f"),
"x" : 1.0,
"y" : {
"z" : 2.0,
"k" : 3.0
}
}
db.collection.find({key:{key1:value1,key2:value2}}) //嚴(yán)格匹配 順序敏感
db.collection.find({key.key1:value1,key.key2:value2}) //靈活
//游標(biāo)
var cursor = db.collection.find();
while(cursor.hasNext())
{
print(cursor.next())
}
while(cursor.hasNext())
{
print(cursor.next().key)
}
cursor.forEach(function(x)
{
print(x)
})
//limit
db.collection.find().limit(num)
//skip
db.collection.find().skip(num).limit(num)
//sort 1升序 -1降序
db.collection.find().sort({key:1})
explain
db.getCollection('runoob').find({x:1}).explain()
//result
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "test.runoob",
"indexFilterSet" : false,
"parsedQuery" : {
"x" : {
"$eq" : 1.0
}
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"x" : {
"$eq" : 1.0
}
},
"direction" : "forward"
},
"rejectedPlans" : []
},
"serverInfo" : {
"host" : "hebin-P1",
"port" : 27017,
"version" : "3.2.22",
"gitVersion" : "105acca0d443f9a47c1a5bd608fd7133840a58dd"
},
"ok" : 1.0
}
//返回結(jié)果包含兩大塊信息您宪,一個(gè)是queryPlanner,即查詢計(jì)劃奠涌,還有一個(gè)是serverInfo宪巨,即MongoDB服務(wù)的一些信息
參數(shù) 含義
plannerVersion 查詢計(jì)劃版本
namespace 要查詢的集合
indexFilterSet 是否使用索引
parsedQuery 查詢條件,此處為x=1
winningPlan 最佳執(zhí)行計(jì)劃
stage 查詢方式铣猩,常見的有COLLSCAN/全表掃描揖铜、IXSCAN/索引掃描、FETCH/根據(jù)索引去檢索文檔达皿、SHARD_MERGE/合并分片結(jié)果天吓、IDHACK/針對(duì)_id進(jìn)行查詢
filter 過濾條件
direction 搜索方向
rejectedPlans 拒絕的執(zhí)行計(jì)劃
serverInfo MongoDB服務(wù)器信息
//參數(shù) executionStats 會(huì)返回最佳執(zhí)行計(jì)劃的一些統(tǒng)計(jì)信息
db.getCollection('runoob').find({x:1}).explain('executionStats')
//result
/* 1 */
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "test.runoob",
"indexFilterSet" : false,
"parsedQuery" : {
"x" : {
"$eq" : 1.0
}
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"x" : {
"$eq" : 1.0
}
},
"direction" : "forward"
},
"rejectedPlans" : []
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 0,
"executionTimeMillis" : 0,
"totalKeysExamined" : 0,
"totalDocsExamined" : 3,
"executionStages" : {
"stage" : "COLLSCAN",
"filter" : {
"x" : {
"$eq" : 1.0
}
},
"nReturned" : 0,
"executionTimeMillisEstimate" : 0,
"works" : 5,
"advanced" : 0,
"needTime" : 4,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"invalidates" : 0,
"direction" : "forward",
"docsExamined" : 3
}
},
"serverInfo" : {
"host" : "hebin-P1",
"port" : 27017,
"version" : "3.2.22",
"gitVersion" : "105acca0d443f9a47c1a5bd608fd7133840a58dd"
},
"ok" : 1.0
}
參數(shù) 含義
executionSuccess 是否執(zhí)行成功
nReturned 返回的結(jié)果數(shù)
executionTimeMillis 執(zhí)行耗時(shí)
totalKeysExamined 索引掃描次數(shù)
totalDocsExamined 文檔掃描次數(shù)
executionStages 這個(gè)分類下描述執(zhí)行的狀態(tài)
stage 掃描方式贿肩,具體可選值與上文的相同
nReturned 查詢結(jié)果數(shù)量
executionTimeMillisEstimate 預(yù)估耗時(shí)
works 工作單元數(shù),一個(gè)查詢會(huì)分解成小的工作單元
advanced 優(yōu)先返回的結(jié)果數(shù)
docsExamined 文檔檢查數(shù)目龄寞,與totalDocsExamined一致
//參數(shù) allPlansExecution 獲取所有執(zhí)行計(jì)劃
索引 MongoDB限制每個(gè)集合上最多有64個(gè)索引
//默認(rèn)_id是索引
//創(chuàng)建索引
db.collection.ensureIndex(key:1) //1升序 -1降序
//查看索引
db.collection.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.runoob"
},
{
"v" : 1,
"key" : {
"name" : 1.0
},
"name" : "name_1", //索引名 默認(rèn) 字段名_排序值
"ns" : "test.runoob"
}
]
//創(chuàng)建索引其它參數(shù)
db.collection.ensureIndex({x:1},{name:"myfirstindex",dropDups:true,background:true,unique:true,sparse:true,v:1,weights:99999})
//參數(shù)說明
1.name表示索引的名稱
2.dropDups表示創(chuàng)建唯一性索引時(shí)如果出現(xiàn)重復(fù)汰规,則將重復(fù)的刪除,只保留第一個(gè)
3.background是否在后臺(tái)創(chuàng)建索引物邑,在后臺(tái)創(chuàng)建索引不影響數(shù)據(jù)庫當(dāng)前的操作溜哮,默認(rèn)為false
4.unique是否創(chuàng)建唯一索引,默認(rèn)false
5.sparse對(duì)文檔中不存在的字段是否不起用索引色解,默認(rèn)false
6.v表示索引的版本號(hào)茂嗓,默認(rèn)為2
7.weights表示索引的權(quán)重
//查看索引大小
db.collection.totalIndexSize()
//刪除索引
db.collection.dropIndex('indexName') //按名稱刪除
db.collection.dropIndexes() //刪除所有索引