一、簡(jiǎn)介
MongoDB 是一個(gè)基于分布式 文件存儲(chǔ)的NoSQL數(shù)據(jù)庫(kù)。由 C++ 語(yǔ)言編寫。旨在為 WEB 應(yīng)用提供可擴(kuò)展的高性能數(shù)據(jù)存儲(chǔ)解決方案。
MongoDB 是一個(gè)介于關(guān)系數(shù)據(jù)庫(kù)和非關(guān)系數(shù)據(jù)庫(kù)之間的產(chǎn)品,是非關(guān)系數(shù)據(jù)庫(kù)當(dāng)中功能最豐富,最像關(guān)系數(shù)據(jù)庫(kù)的。
關(guān)系型數(shù)據(jù)庫(kù)(SQLite、Oracle、mysql)特點(diǎn)
- 關(guān)系模型指的是二維表格模型
- 通用的SQL語(yǔ)言是的操作關(guān)系型數(shù)據(jù)庫(kù)非常方便
- 固定的表結(jié)構(gòu)
MongoDB 特點(diǎn)
- 模式自由 :可以把不同結(jié)構(gòu)的文檔存儲(chǔ)在同一個(gè)數(shù)據(jù)庫(kù)里
- 面向集合的存儲(chǔ):適合存儲(chǔ) JSON風(fēng)格文件的形式,
- 完整的索引支持:對(duì)任何屬性可索引,
- 復(fù)制和高可用性:支持服務(wù)器之間的數(shù)據(jù)復(fù)制,支持主-從模式及服務(wù)器之間的相互復(fù)制。復(fù)制的主要目的是提供冗余及自動(dòng)故障轉(zhuǎn)移。
- 自動(dòng)分片:支持云級(jí)別的伸縮性:自動(dòng)分片功能支持水平的數(shù)據(jù)庫(kù)集群,可動(dòng)態(tài)添加額外的機(jī)器。
- 豐富的查詢:支持豐富的查詢表達(dá)方式,查詢指令使用JSON形式的標(biāo)記,可輕易查詢文檔中的內(nèi)嵌的對(duì)象及數(shù)組。
- 快速就地更新:查詢優(yōu)化器會(huì)分析查詢表達(dá)式,并生成一個(gè)高效的查詢計(jì)劃。
- 高效的傳統(tǒng)存儲(chǔ)方式:支持二進(jìn)制數(shù)據(jù)及大型對(duì)象(如照片或圖片)
二、MongoDB 的基本操作
2.1 創(chuàng)建數(shù)據(jù)庫(kù)
語(yǔ)法
MongoDB創(chuàng)建數(shù)據(jù)庫(kù)的語(yǔ)法格式如下:
use DATABASE_NAME
如果數(shù)據(jù)庫(kù)不存在,則指向數(shù)據(jù)庫(kù),但不創(chuàng)建(等待實(shí)際數(shù)據(jù)入庫(kù)后創(chuàng)建),否則切換到指定的數(shù)據(jù)庫(kù)。
示例
創(chuàng)建數(shù)據(jù)庫(kù)
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> use test
switched to db test
> db
test
>
查看當(dāng)前數(shù)據(jù)庫(kù)名稱
>db
查看當(dāng)前db中所有的collection
>show collections
剛創(chuàng)建的數(shù)據(jù)庫(kù) test 并不在數(shù)據(jù)庫(kù)的列表中,要顯示它,我們需要向 test 數(shù)據(jù)庫(kù)插入一些數(shù)據(jù)
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> db.message.insert({"name":"simon","msg":"hello"})
2018-12-01T13:38:28.225+0800 E QUERY [js] SyntaxError: illegal character @(shell):1:18
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
2.2 刪除數(shù)據(jù)庫(kù)
語(yǔ)法
MongoDB 刪除數(shù)據(jù)庫(kù)的語(yǔ)法格式如下:
db.dropDatabase()
刪除當(dāng)前數(shù)據(jù)庫(kù),默認(rèn)為 test,你可以使用 db 命令查看當(dāng)前數(shù)據(jù)庫(kù)名
示例
查看所有數(shù)據(jù)庫(kù)
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
mytest 0.000GB
> db
mytest
> show collections
message
刪除當(dāng)前數(shù)據(jù)庫(kù) mytest
> db.dropDatabase()
{ "dropped" : "mytest", "ok" : 1 }
檢查數(shù)據(jù)庫(kù)列表
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
2.3 創(chuàng)建集合
語(yǔ)法
基本的 createCollection() 命令語(yǔ)法如下:
db.createCollection(name, options)
在命令中, name 是要?jiǎng)?chuàng)建的集合的名稱. Options 是一個(gè)文檔,用于指定配置的集合
| 參數(shù) | 類型 | 描述 |
|---|---|---|
| Name | String | 要?jiǎng)?chuàng)建的集合名稱 |
| Options | Document | (可選)指定有關(guān)內(nèi)存大小和索引選項(xiàng) |
選項(xiàng)??參數(shù)是可選的,所以只需要到指定的集合名稱。以下是可以使用的選項(xiàng)列表:
| 字段 | 類型 | 描述 |
|---|---|---|
| capped | Boolean | (可選)如果為true,則啟用封頂集合。封頂集合是固定大小的集合,當(dāng)它達(dá)到其最大大小,會(huì)自動(dòng)覆蓋最早的條目。如果指定true,則需要也指定size字段。 |
| autoIndexID | Boolean | (可選)如果為true,自動(dòng)創(chuàng)建索引_id字段, 默認(rèn)值是false。 |
| size | number | (可選)指定集合最大可使用字節(jié)。如果封頂如果是 true,那么你還需要指定這個(gè)字段。 |
| max | number | (可選)指定封頂集合允許在文件的最大數(shù)量。Size限制優(yōu)先于此限制。如果一個(gè)封頂集合達(dá)到大小size限制,未達(dá)到文件的最大數(shù)量,MongoDB刪除舊的文件。如果您更喜歡使用max,確保為上限的集合所需的大小限制,足以包含文檔的最大數(shù)量。 |
當(dāng)插入文檔,MongoDB 第一檢查大小字段封頂集合,然后它會(huì)檢查最大的字段。
示例
createCollection() 方法不使用選項(xiàng)的示例如下:
> use mytest
switched to db mytest
> db.createCollection("mycollection")
{ "ok" : 1 }
> show collections
mycollection
createCollection() 方法使用選項(xiàng)的示例如下:
> db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )
{ "ok" : 1 }
> show collections
log
mycollection
可以不需要?jiǎng)?chuàng)建集合。當(dāng)插入一些文檔自動(dòng)創(chuàng)建的集合。
2.4 刪除集合
語(yǔ)法
drop() 命令的基本語(yǔ)法如下
db.COLLECTION_NAME.drop()
示例
現(xiàn)在刪除集合名稱為 mycollection
> show collections
log
mycollection
> db.mycollection.drop()
true
> show collections
log
drop() 方法將返回 true,如果選擇成功收集被丟棄,否則將返回 false
2.5 插入文檔
要插入數(shù)據(jù)到 MongoDB 集合,需要使用 MongoDB 的 insert() 或 save() 方法
語(yǔ)法
insert() 命令的基本語(yǔ)法如下:
db.COLLECTION_NAME.insert(document)
save() 命令的基本語(yǔ)法如下:
db.COLLECTION_NAME.save(document)
示例
執(zhí)行下面的命令插入文檔
db.mycol.insert(
[
{
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials itcast',
url: 'http://www.itcast.cn',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
},
{
title: 'MySQL Overview',
description: 'MySQL is sql database',
by: 'tutorials itcast',
url: 'http://www.itcast.cn',
tags: ['MySQL', 'database', 'SQL'],
likes: 40
}
]
)
插入文檔中,如果我們不指定_id參數(shù),然后MongoDB 本文檔分配一個(gè)唯一的ObjectId。
> db.mycol.find().pretty()
{
"_id" : ObjectId("5c022988c6e6fc84a60212c1"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials itcast",
"url" : "http://www.itcast.cn",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("5c0229c7c6e6fc84a60212c2"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials itcast",
"url" : "http://www.itcast.cn",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
_id 是12個(gè)字節(jié)的十六進(jìn)制數(shù),唯一一個(gè)集合中的每個(gè)文檔。 12個(gè)字節(jié)被劃分如下:
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
2.6 查詢文檔
語(yǔ)法
基本的find()方法語(yǔ)法如下:
db.COLLECTION_NAME.find()
示例
> db.mycol.find().pretty()
{
"_id" : ObjectId("5c022988c6e6fc84a60212c1"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials itcast",
"url" : "http://www.itcast.cn",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("5c0229c7c6e6fc84a60212c2"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials itcast",
"url" : "http://www.itcast.cn",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
結(jié)果顯示在一個(gè)格式化的方式,可以使用 pretty() 方法。
| 操作 | 語(yǔ)法 | 例子 |
|---|---|---|
| Equality | `{<key>:<value>}`` | db.mycol.find({"by":"tutorials itcast"}).pretty() |
| Less Than | {<key>:{$lt:<value>}} |
db.mycol.find({"likes":{$lt:50}}).pretty() |
| Less Than Equals | {<key>:{$lte:<value>}} |
db.mycol.find({"likes":{$lte:50}}).pretty() |
| Greater Than | {<key>:{$gt:<value>}}
|
db.mycol.find({"likes":{$gt:50}}).pretty() |
| Greater Than Equals | {<key>:{$gte:<value>}} |
db.mycol.find({"likes":{$gte:50}}).pretty() |
| Not Equals | {<key>:{$ne:<value>}} |
db.mycol.find({"likes":{$ne:50}}).pretty() |
AND 在MongoDB中用法:
語(yǔ)法
在 find() 方法,如果通過多個(gè)鍵分離',',那么 MongoDB 處理 AND 條件。AND 基本語(yǔ)法如下所示:
db.mycol.find({key1:value1, key2:value2}).pretty()
示例
> db.mycol.find({"by":"tutorials itcast","title": "MongoDB Overview"}).pretty()
{
"_id" : ObjectId("5799c3eb235910620b89c674"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials itcast",
"url" : "http://www.itcast.cn",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
>
對(duì)于上面給出的例子相當(dāng)于where子句 where by='tutorials itcast' AND title='MongoDB Overview',可以通過任意數(shù)量的鍵值對(duì)在 find 子句。
OR 在MongoDB的用法
語(yǔ)法
OR條件的基礎(chǔ)上要查詢文件,需要使用$or關(guān)鍵字。OR 基本語(yǔ)法如下所示:
>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
示例
下面給出的例子將顯示所有的教程,標(biāo)題是“MongoDB Overview'或'MySQL Overview'
>db.mycol.find({
$or: [
{
"title": "MySQL Overview"
},
{
"title": "MongoDB Overview"
}
]
}).pretty()
{
"_id" : ObjectId("57cefded600d5bb1e2acdb70"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials itcast",
"url" : "http://www.itcast.cn",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("57cefdf7600d5bb1e2acdb71"),
"title" : "MySQL Overview",
"description" : "MySQL is sql database",
"by" : "tutorials itcast",
"url" : "http://www.itcast.cn",
"tags" : [
"MySQL",
"database",
"SQL"
],
"likes" : 40
}
>
AND 和 OR 一起使用
示例
面給出的例子將顯示 喜愛數(shù)高于50,其標(biāo)題是MongoDB Overview或者是itcast所寫 。等效于 SQL where子句 為 where likes>10 AND (by = 'itcast' OR title = 'MongoDB Overview')
db.mycol.find({
"likes": {
$gt: 50
},
$or: [
{
"by": "tutorials itcast"
},
{
"title": "MongoDB Overview"
}
]
}).pretty()
{
"_id" : ObjectId("57cefded600d5bb1e2acdb70"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials itcast",
"url" : "http://www.itcast.cn",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
>
2.7 更新文檔
MongoDB 使用 update() 和 save() 方法來(lái)更新集合中的文檔。接下來(lái)讓我們?cè)敿?xì)來(lái)看下兩個(gè)函數(shù)的應(yīng)用及其區(qū)別。
2.7.1 update() 更新文檔
語(yǔ)法
update() 方法的基本語(yǔ)法如下:
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
參數(shù)說明:
- query : update的查詢條件,類似sql update查詢內(nèi)where后面的。
- update : update的對(duì)象和一些更新的操作符(如
inc...)等,也可以理解為sql update查詢內(nèi)set后面的
- upsert : 可選,這個(gè)參數(shù)的意思是,如果不存在update的記錄,是否插入objNew,true為插入,默認(rèn)是false,不插入。
- multi : 可選,mongodb 默認(rèn)是false,只更新找到的第一條記錄,如果這個(gè)參數(shù)為true,就把按條件查出來(lái)多條記錄全部更新。
- writeConcern :可選,拋出異常的級(jí)別。
示例
下面的例子將設(shè)置標(biāo)題MongoDB Overview的文件,更新其標(biāo)題是New MongoDB Tutorial
> db.mycol.update({
'title': 'MongoDB Overview'
},
{
$set: {
'title': 'New MongoDB Tutorial'
}
})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.mycol.find().pretty()
{
"_id" : ObjectId("5799c3eb235910620b89c674"),
"title" : "New MongoDB Tutorial",
"description" : "MongoDB is no sql database",
"by" : "tutorials itcast",
"url" : "http://www.itcast.cn",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("5799c3f3235910620b89c675"),
"title" : "MySQL Overview",
"description" : "MySQL is sql database",
"by" : "tutorials itcast",
"url" : "http://www.itcast.cn",
"tags" : [
"MySQL",
"database",
"SQL"
],
"likes" : 40
}
MongoDB默認(rèn)將只更新單一的文件,來(lái)更新多個(gè)你需要設(shè)置參數(shù)置multi為true
>db.mycol.update({'by':'tutorials itcast'},{$set:{'by':'itcast'}},{multi:true})
2.7.2 save() 更新文檔
save() 方法覆蓋原有的文檔 或者 插入新的文檔
語(yǔ)法
MongoDB 的 save() 方法的基本語(yǔ)法如下:
db.collection.save(
<document>,
{
writeConcern: <document>
}
)
參數(shù)說明:
document : 要存儲(chǔ)的文檔數(shù)據(jù)。
writeConcern :可選,拋出異常的級(jí)別。
例子
下面的例子將取代文件具有_id為 '5799c3eb235910620b89c674'
>db.mycol.save(
{
"_id" : ObjectId("5799c3eb235910620b89c674"),
"title":"itcast New Topic",
"by":"itcast"
}
)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.mycol.find().pretty()
{
"_id" : ObjectId("5799c3eb235910620b89c674"),
"title" : "itcast New Topic",
"by" : "itcast"
}
{
"_id" : ObjectId("5799c3f3235910620b89c675"),
"title" : "MySQL Overview",
"description" : "MySQL is sql database",
"by" : "tutorials itcast",
"url" : "http://www.itcast.cn",
"tags" : [
"MySQL",
"database",
"SQL"
],
"likes" : 40
}}
>
2.8 刪除文檔
語(yǔ)法
MongoDB 刪除文檔的函數(shù)是remove()
db.collection.remove(
<query>,
{
justOne: <boolean>,
writeConcern: <document>
}
)
參數(shù)說明:
- justOne : (可選)如果設(shè)為 true 或 1,則只刪除一個(gè)文檔。默認(rèn)false
- writeConcern :(可選)拋出異常的級(jí)別。
例子
考慮以下數(shù)據(jù)myLimit集合:
> db.myLimit.insert(
[
{ "_id" : 0 },
{ "_id" : 1 },
{ "_id" : 2 },
{ "_id" : 3 },
{ "_id" : 4 }
]
)
> db.myLimit.find()
{ "_id" : 0 }
{ "_id" : 1 }
{ "_id" : 2 }
{ "_id" : 3 }
{ "_id" : 4 }
下面的例子將刪除所有的文檔,其_id 是 3
> db.myLimit.remove({"_id" : 3})
WriteResult({ "nRemoved" : 1 })
> db.myLimit.find()
{ "_id" : 0 }
{ "_id" : 1 }
{ "_id" : 2 }
{ "_id" : 4 }
如果有多個(gè)記錄且要?jiǎng)h除的只有第一條記錄,那么設(shè)置remove()方法中justOne參數(shù)設(shè)置1或者是true
>db.myLimit.remove({"_id" : {$gt:0}},1)
WriteResult({ "nRemoved" : 1 })
如果不指定刪除條件,然后MongoDB將從集合中刪除整個(gè)文檔。這相當(dāng)于SQL的truncate命令。
> db.myLimit.remove({})
WriteResult({ "nRemoved" : 3 })
2.8 索引
索引通常能夠極大的提高查詢的效率,如果沒有索引,MongoDB在讀取數(shù)據(jù)時(shí)必須掃描集合中的每個(gè)文檔并選取那些符合查詢條件的記錄,花費(fèi)的時(shí)間會(huì)很多
語(yǔ)法
ensureIndex()方法基本語(yǔ)法格式如下所示:
db.COLLECTION_NAME.ensureIndex({KEY:1})
語(yǔ)法中 Key 值為你要?jiǎng)?chuàng)建的索引字段,1為指定按升序創(chuàng)建索引,-1即為降序。
MongoDB 提供了一個(gè) explain 命令讓我們獲知系統(tǒng)如何處理查詢請(qǐng)求。利用 explain 命令,可以很好地觀察系統(tǒng)如何使用索引來(lái)加快檢索,同時(shí)可以針對(duì)性優(yōu)化索引。
示例
1. 插入測(cè)試數(shù)據(jù)
db.inventory.insert([
{ "_id" : 1, "item" : "f1", type: "food", quantity: 500 },
{ "_id" : 2, "item" : "f2", type: "food", quantity: 100 },
{ "_id" : 3, "item" : "p1", type: "paper", quantity: 200 },
{ "_id" : 4, "item" : "p2", type: "paper", quantity: 150 },
{ "_id" : 5, "item" : "f3", type: "food", quantity: 300 },
{ "_id" : 6, "item" : "t1", type: "toys", quantity: 500 },
{ "_id" : 7, "item" : "a1", type: "apparel", quantity: 250 },
{ "_id" : 8, "item" : "a2", type: "apparel", quantity: 400 },
{ "_id" : 9, "item" : "t2", type: "toys", quantity: 50 },
{ "_id" : 10, "item" : "f4", type: "food", quantity: 75 }])
2. 無(wú)索引查詢
db.inventory.find(
{
quantity: {
$gte: 100,
$lte: 200
}
}
).explain("executionStats")
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "mytest.inventory",
"indexFilterSet" : false,
"parsedQuery" : {
"$and" : [
{
"quantity" : {
"$lte" : 200
}
},
{
"quantity" : {
"$gte" : 100
}
}
]
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"$and" : [
{
"quantity" : {
"$lte" : 200
}
},
{
"quantity" : {
"$gte" : 100
}
}
]
},
"direction" : "forward"
},
"rejectedPlans" : [ ]
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 3,
"executionTimeMillis" : 48,
"totalKeysExamined" : 0,
"totalDocsExamined" : 10,
"executionStages" : {
"stage" : "COLLSCAN",
"filter" : {
"$and" : [
{
"quantity" : {
"$lte" : 200
}
},
{
"quantity" : {
"$gte" : 100
}
}
]
},
"nReturned" : 3,
"executionTimeMillisEstimate" : 28,
"works" : 12,
"advanced" : 3,
"needTime" : 8,
"needYield" : 0,
"saveState" : 1,
"restoreState" : 1,
"isEOF" : 1,
"invalidates" : 0,
"direction" : "forward",
"docsExamined" : 10
}
},
"serverInfo" : {
"host" : "DESKTOP-GVTQ3ND",
"port" : 27017,
"version" : "4.0.4",
"gitVersion" : "f288a3bdf201007f3693c58e140056adf8b04839"
},
"ok" : 1
}
- COLLSCAN:如果你仔細(xì)一看,知道是CollectionScan,就是所謂的“集合掃描”,看到集合掃描 相當(dāng)于 sql數(shù)據(jù)庫(kù)中的table scan
- nReturned:就是所謂的numReturned,就是說最后返回的num個(gè)數(shù),從圖中可以看到,就是最終返回了三條
- docsExamined:就是documentsExamined,檢查了10個(gè)documents。
從上面三個(gè)信息中得出,docsExamined 10條數(shù)據(jù),最終才返回nReturned 3條,說明做了7條數(shù)據(jù)scan的無(wú)用功,那么這個(gè)時(shí)候問題就來(lái)了!
3. 創(chuàng)建索引
在quality字段之上添加索引,如下:
db.inventory.createIndex({ quantity: 1})
db.inventory.find(
{ quantity: { $gte: 100, $lte: 200 } }
).explain("executionStats")
結(jié)果如下:
db.inventory.find( { quantity: { $gte: 100, $lte: 200 } } ).explain("executionStats")
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "mytest.inventory",
"indexFilterSet" : false,
"parsedQuery" : {
"$and" : [
{
"quantity" : {
"$lte" : 200
}
},
{
"quantity" : {
"$gte" : 100
}
}
]
},
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"quantity" : 1
},
"indexName" : "quantity_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"quantity" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"quantity" : [
"[100.0, 200.0]"
]
}
}
},
"rejectedPlans" : [ ]
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 3,
"executionTimeMillis" : 0,
"totalKeysExamined" : 3,
"totalDocsExamined" : 3,
"executionStages" : {
"stage" : "FETCH",
"nReturned" : 3,
"executionTimeMillisEstimate" : 0,
"works" : 4,
"advanced" : 3,
"needTime" : 0,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"invalidates" : 0,
"docsExamined" : 3,
"alreadyHasObj" : 0,
"inputStage" : {
"stage" : "IXSCAN",
"nReturned" : 3,
"executionTimeMillisEstimate" : 0,
"works" : 4,
"advanced" : 3,
"needTime" : 0,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"invalidates" : 0,
"keyPattern" : {
"quantity" : 1
},
"indexName" : "quantity_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"quantity" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"quantity" : [
"[100.0, 200.0]"
]
},
"keysExamined" : 3,
"seeks" : 1,
"dupsTested" : 0,
"dupsDropped" : 0,
"seenInvalidated" : 0
}
}
},
"serverInfo" : {
"host" : "DESKTOP-GVTQ3ND",
"port" : 27017,
"version" : "4.0.4",
"gitVersion" : "f288a3bdf201007f3693c58e140056adf8b04839"
},
"ok" : 1
}
當(dāng)我們執(zhí)行完createindex之后,再次explain,4個(gè)重要的parameters參數(shù)就出來(lái)了:
- IXSCAN:這個(gè)時(shí)候再也不是所謂的COLLSCAN了,而是IndexScan,這就說明我們已經(jīng)命中索引了
- nReturned, totalDocsExamined, totalKeysExamined:從中可以看到三個(gè)參數(shù)都是3,這就說明我們的mongodb查看了3個(gè)key,3個(gè)document,返回3個(gè)文檔,這個(gè)就是所謂的高性能所在。
4. 查看索引
db.inventory.getIndexes()
三、數(shù)據(jù)類型
MongoDB 支持如下數(shù)據(jù)類型:
- String:字符串。存儲(chǔ)數(shù)據(jù)常用的數(shù)據(jù)類型。在 MongoDB 中,UTF-8 編碼的字符串才是合法的。
- Integer:整型數(shù)值。用于存儲(chǔ)數(shù)值。根據(jù)你所采用的服務(wù)器,可分為 32 位或 64 位。
- Boolean:布爾值。用于存儲(chǔ)布爾值(真/假)。
- Double:雙精度浮點(diǎn)值。用于存儲(chǔ)浮點(diǎn)值。
- Min/Max keys:將一個(gè)值與 BSON(二進(jìn)制的 JSON)元素的最低值和最高值相對(duì)比。
- Arrays:用于將數(shù)組或列表或多個(gè)值存儲(chǔ)為一個(gè)鍵。
- Timestamp:時(shí)間戳。記錄文檔修改或添加的具體時(shí)間。
- Object:用于內(nèi)嵌文檔。
- Null:用于創(chuàng)建空值。
- Symbol:符號(hào)。該數(shù)據(jù)類型基本上等同于字符串類型,但不同的是,它一般用于采用特殊符號(hào)類型的語(yǔ)言。
- Date:日期時(shí)間。用 UNIX 時(shí)間格式來(lái)存儲(chǔ)當(dāng)前日期或時(shí)間。你可以指定自己的日期時(shí)間:創(chuàng)建 Date 對(duì)象,傳入年月日信息。
- Object ID:對(duì)象 ID。用于創(chuàng)建文檔的 ID。
- Binary Data:二進(jìn)制數(shù)據(jù)。用于存儲(chǔ)二進(jìn)制數(shù)據(jù)。
- Code:代碼類型。用于在文檔中存儲(chǔ) JavaScript 代碼。
- Regular expression:正則表達(dá)式類型。用于存儲(chǔ)正則表達(dá)式。