MongoDB

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

jsx 复制代码
{
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
Database Database
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 the getIndexes command 通過 getIndexes 指令來驗證

JSON 复制代码
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 ![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/87d7d7a5a8ee4e389cf5949ebc30692f.png)

Create Operations

  • Insert operations add new document to a collection 插入操作將新文檔添加到文檔集中
  • If the collection does ++not currently exist++, the insert operations create it

用於將文檔插入到集和中

JSON 复制代码
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 ```JSON {_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 returned

JSON 复制代码
db.collectionName.find(<(query)><(projection))

!example

Displays all staff and supervisors who work on or supervise projects over the last 3 years

JSON 复制代码
db.projectCollection.find( {"pyears": { $gte:3 } }, { staff:1, supervisors:1 })

!done\] Output ```JSON { "\_id" : ObjectId("5dabb758d16c90c5b6007ac4"), staff: [ {fname: "John", lname: "Smith", hours: 28.4}, {fname: "Joyce", lname: "Marry", hours: 23.4}], supervisors:["James Brown", "Louis Lampard"], ```

!code

JSON 复制代码
{
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(,,)` > \[!col

!code

JSON 复制代码
{
  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 ```JSON 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(,)` \[!example\] Deletes all projects whoes finished status is 1 and ongoing status is 0 ```JSON db.projectCollection.deleteMany( {"status.finished":1, "status.ongoing":0} ) ```

deleteOne
deleteMany ()
drop()
相关推荐
熏鱼的小迷弟Liu1 小时前
【Redis】Redis Zset实现原理:跳表+哈希表的精妙设计
数据库·redis·散列表
淋一遍下雨天2 小时前
Spark Streaming核心编程总结(四)
java·开发语言·数据库
zru_96022 小时前
Windows 安装 MongoDB 教程
数据库·mongodb
数据与后端架构提升之路3 小时前
深度解析如何将图像帧和音频片段特征高效存储到向量数据库 Milvus
数据库·opencv·音视频
创码小奇客3 小时前
MongoDB 事务:数据世界的守护者联盟全解析
spring boot·mongodb·trae
20242817李臻3 小时前
李臻20242817_安全文件传输系统项目报告_第9周
数据库·安全
小白考证进阶中3 小时前
0基础可以考MySQL OCP么?备考时间需要多久?
数据库·mysql·开闭原则
观无4 小时前
Redis远程链接应用案例
数据库·redis·缓存·c#
星星点点洲4 小时前
【缓存与数据库结合方案】伪从技术 vs 直接同步/MQ方案的深度对比
数据库·缓存
努力奋斗的小杨4 小时前
学习MySQL的第十二天
数据库·笔记·学习·mysql·navicat