Document-Based NoSQL System
- MongoDB is a general purpose 通用的, document-based, distributed database built for modern application developers and for the cloud era
- MongoDB is developed by MongoDB Inc and licensed under the Server Side Public License (SSPL)
- A record in MongoDB is a document, which is a data structure composed of key value pairs similar to the structure of JSON objects. 一條記錄就是一個文檔,它是由鍵值對組成的資料結構,類似JSON物件的結構
Example
{ title: "Post Title 1", body: "Body of post", category: "News", likes: 1, tags: ["news","events"], date: Date() }
優點
- Popularity 受歡迎
- High performance 高性能
- High availability 高可用性
- Horizontal Scalability 橫向可拓展性
- Rich query language 豐富的查詢語言
- Support for Multiple 支持多個
- Storage Engines 儲存引擎
Terminology and Concept: SQL and MongoDB
SQL Terms/ Concepts | MongoDB Terms/ Concepts |
---|---|
|
|
Table | Collection |
Row | Document |
Column | Field |
Index | Index |
Table joins | $lookup |
Primary key | Primary key |
SQL vs Document database:
SQL databases are considered relational databases. They store related data in separate tables單獨的表格. When data is needed, it is queried from multiple tables to join the data back together.MongoDB stores data in flexible documents. Instead of having multiple tables you can simply keep all of your related data together. This makes reading your data very fast. MongoDB 將資料儲存在靈活的文件中。您可以簡單地將所有相關資料保存在一起,而不需要使用多個表。這使得讀取資料的速度非常快。
You can still have multiple groups of data too. In MongoDB, instead of tables these are called collections. 您仍然可以擁有多組資料。在 MongoDB 中,這些稱為集合,而不是表
The core difference comes from the fact that relational databases define columns at the table level whereas a document-oriented database defines its fields at the document level.
-> each document within a collection can have its own unique set of fields. 每個文件都可以有自己獨特的欄位集
a collection isn’t strict about what goes in it (its schema is flexible/dynamic). 對於要放入的內容並不嚴格(模式是彈性的動態的)
Alternatives
Every document must have a unique _d field (ObjectId類型的value)
By default, the _id field is indexed. You can verify this through thegetIndexes
command 通過getIndexes
指令來驗證db.unicorns.getIndexes()
Collection and Document in MongoDB
Basic Datatypes
Datatype | Example |
---|---|
Null | {“x”: null} |
Boolean | {“x”: true} |
Number | {“x”: 3.14} {“x”: 3} |
String | {“x”: “foobar”} |
Data | {“x”: new Date()} |
Regular expression | {“x”: /foobar/} |
Array | {“x”: [“a”, “b”, “c”]} |
Embedded Document | {“x”: {“foo”:“bar”}} |
Object ID | {“x”: Objectid()} |
BSON and JSON
- In MongoDB, database holds collection of documents which are in JSON-style (JavaScript Object Notation Style) format 保存著 JSON 風格的文檔
- JSON is an open, human and machine-readable standard to transmit data objects consisting of attributes-value pairs 開放的,人類和機器可讀的,用於傳輸由以下內容組成的數據對象的屬性和值對
- MongoDB represents JSON documents in binary-encoded format called Binary JSON (BSON - [bee · sahn]) behind the scene 二進制編碼
JavaScript Object Notation Structure
Binary JSON (BSON)
In BSON: Data is represented in field - value pairs [field - value]
A field/value pair consists of a field name followed by a colon, followed by a value – example:
name: “Joseph”
Fields are separated by commas – example:
name: “Joseph”, “course”: “Databases”, score:80
Curly braces hold objects (documents) – example: 括號表示對象
{name: “Joseph”, “course”: “Database”, score: 80}
Embedded document 嵌入文件 - example:
{name: “Joseph”, courses:{course1: “databases”, course2: “python”}}
Any array is stored in brackets [] - example:
{name: “Joseph”, courses:[“databases”,“programming”]}
An array of (one or more) embedded document contains documents embedded in the array - example:
{name: “Joseph”, courses:[{course1: “databases”, courses2: “python”}]}
The *_id Field
Title
- Each document in a collection requires a unique _id field 集合中的每個文檔都需要一個唯一的_id 字段
- The _id field acts as a primary key to the collection 作為集合的主鍵
- If an inserted document omits忽略 the _id field, an Objectid is automatically generated for the _id field
- The _id field is always the first field in the document
- The _id field may contain BSON data type except arrays
MongoDB CRUD Operations
Query Operators
Name | Description |
---|---|
$eq | Matches values that are equal to specified value |
$gt | Matches values that are greater than a specified value |
$gte | Matches values that greater than or equal to specified value |
$in | Matches any of the values specified in an array |
$lt | Matches values that are less than a specified value |
$lte | Matches values that are less than or equal to specified value |
$ne | Matches all values that are not equal to a specified value |
$nin | Matches none of the values specified in an array |
[!example]+ Example
Create Operations
- Insert operations add new document to a collection 插入操作將新文檔添加到文檔集中
- If the collection does not currently exist, the insert operations create it
用於將文檔插入到集和中
db. collectionName. insertOne (<documents>)
db. collectionName. insertMany ([<documents>])
db. collectionName. insert (<documents>)
[!example]+ Project collection example
db. movies. insertMany ([{"title": "Ghostbusters"},{"title": "Blade Runner"}]);
db. movies. find ()
[!done] Output
{"_id": ObjectId ("572630ba11722fac4b6b4996"), "title": "Ghostbusters"}
{"_id":ObjectId("572630ba11722fac4b6b4997"),"title":"E.T"}
{"_id":ObjectId("572630ba11722fac4b6b4998"),"title":"Blade Runner"}
insertOne
insertMany ()
[!code]
db.movies.find()
[!done]+ output
{_id:ObjectId("61a403fe076beaa055febc15"),title:'Ghostbusters'} {_id: ObjectId ("61a403fe076beaa055febc15"), title: 'E.T'} {_id: ObjectId ("61a403fe076beaa055febc15"), title: 'Blade Runner'}
ordered operations
Automaticity is at the level of document 自動性指的是文件層面的
Read Operations
- Read operation retrieves檢索 documents from a collection – queries a collection for documents
- The following methods are used to read document in a collection
[!cite]+ Summary
[!col]
[!important]
query specifies selection criteria using query operators, projection specifies fields to be returneddb.collectionName.find(<(query)><(projection))
[!example]
Displays all staff and supervisors who work on or supervise projects over the last 3 yearsdb.projectCollection.find( {"pyears": { $gte:3 } }, { staff:1, supervisors:1 })
[!done] Output
{ "\_id" : ObjectId("5dabb758d16c90c5b6007ac4"), staff: [ {fname: "John", lname: "Smith", hours: 28.4}, {fname: "Joyce", lname: "Marry", hours: 23.4}], supervisors:["James Brown", "Louis Lampard"],
[!code]
{ pname: "ProjectX", plocation: "Frankfurt", pyears: 3, staff:[ {fname: "John", Iname: "Smith", hours: 28.4}, {fname;"Jocye", Iname:: Marry, hours: 23.4} ], supervisors:["James Brown", "Louis Lampard"], status:{finished: 1, ongoing: 0, comment: "none"} })
Querying Document: using “find
”
Querying Document using “find
”+<(projection)>
Querying on Embedded/Nested Document
Querying on Array
Querying an Array of Embedded Documents
Update Operations
- Modify existing document in collection
- The following method are used to update documents in a collection
[!quote]+ Summary
[!info] filter denotes the selection criteria for the update action implies the modification to apply, and options implies additional al actions that can be assigned to the operation
db.collectionName.updateMany(<filter>,<update action>,<options>)
[!col]
[!code]
{ pname: "ProjectX", plocation: "Frankfurt", pyears: 3, staff:[ {fname: "John", Iname: "Smith", hours: 28.4}, {fname;"Jocye", Iname:: Marry, hours: 23.4} ], supervisors:["James Brown", "Louis Lampard"], status:{finished: 1, ongoing: 0, comment: "none"} })
[!done] Updates Updates the finished and ongoing status of all projects whose number of years is >= 5 to 1 and 0, respectively
db.pojectCollection.updateMany( {"pyears":{$gte:5}}, {$set:{"status.finished":1}} )
updateOne
updateOne
: “$set
” Operator
Note: “
$set
” sets the value of a field. If the field does not yet exist, it will be created. If the user decides that he enjoys a different book, “$ set” can be used again to change the value
“
$set
” can change the type of the key it modifies (in above example from a value to an array) 更改鍵的類型
$unset
operator
$inc
Operator
“
$inc
” will create the field “pageview” if it does not exist and assign value “1” to it
$push
operator for Array - Adding Element with
$push
will create an array “comments” if it does not exist
$addToSet
Array Operators - Adding Element
在这里插入图片描述
避免添加重複的array elements 因為如果遇到重複的會被跳過,重複的值不會被成功加入進去
$pull
Array Operators - remove element
[!attention]
{"$pop" : {"key" : 1}}
removes an element from the end of the array.
{"$ pop" : {"key" : -1}}
removes it from the beginning.
Positional Array Modification
upsert
Operator
- An
upsert
is a special type of update. If no document is found that matches the filter, a new document will be created by combining the criteria and updated documents - If a matching document is found, it will be updated normally
updating Multiple Documents
insertMany()
Delete Operation
- Delete operations remove documents from a collection
- The following methods are used to remove documents from a collection
[!hint] Filter specifies deletion criteria標準 using query operators, and options specifies additional optional actions that can be assigned to the operation 使用查詢運算符指定刪除標准 options則指定額外的可選操作
db.collectionName.deleteMany(<filter>,<options>)
[!example] Deletes all projects whoes finished status is 1 and ongoing status is 0
db.projectCollection.deleteMany( {"status.finished":1, "status.ongoing":0} )