天天看點

【MongoDB學習筆記】-使用 MongoDB 進行 CRUD 操作(上)

​​​​​

作者:幻好​

概述

MongoDB 是一種持久化的面向文檔的資料庫,用于以文檔的形式存儲和處理資料。

【MongoDB學習筆記】-使用 MongoDB 進行 CRUD 操作(上)

與其他的資料庫管理系統一樣,MongoDB 可以通過四種基本類型的資料操作來管理資料并與資料互動:

  • ​C​:建立操作,涉及将資料寫入資料庫
  • ​R​:讀取操作,查詢資料庫以從中檢索資料
  • ​U​:更新操作,更改資料庫中已存在的資料
  • ​D​:删除操作,從資料庫中永久删除資料

以上四種操作統稱為 CRUD 操作,本文主要講解這四種操作的原理和指令等相關知識。

具體操作

連接配接 MongoDB Server

首先在操作前,先連接配接到本地或遠端可使用的 MongoDB Server ,如下圖:

【MongoDB學習筆記】-使用 MongoDB 進行 CRUD 操作(上)

連接配接 MongoDB 資料庫成功後,就可以開始建立新文檔(​

​documents​

​)。

建立文檔

首先先重點介紹如何在 MongoDB 中建立資料文檔(​

​documents​

​)

比如建立一個東方明珠景點對象,可能相關資訊有所在國家,城市,坐标等:

{
    "name": "東方明珠",
    "country": "中國",
    "city": "上海",
    "location": {
        "lat": 121.537,
        "lng": 31.258
    }
}      

MongoDB 的文檔是用 ​

​BSON​

​​ 編寫的, ​

​BSON​

​​ 是 ​

​JSON​

​​ 的二進制形式,是友善可讀的資料格式。 ​

​BSON​

​​ 或 ​

​JSON​

​​ 文檔中的所有資料都表示為采用 ​

​field: value​

​ 形式的字段和值對。

該文檔由四個字段組成,首先是景點的名稱,其次是城市和國家。所有這三個字段都包含字元串。最後一個字段坐标:location,是一個嵌套文檔,詳細說明了景點的位置坐标。

insertOne

使用 ​

​insertOne​

​​ 方法将此文檔插入到名為 ​

​spots​

​​ 的新集合中。顧名思義,​

​insertOne​

​ 用于建立單個文檔,而不是一次建立多個文檔。

在指令行中,運作以下指令:

db.spots.insertOne(
    {
        "name": "東方明珠",
        "country": "中國",
        "city": "上海",
        "location": {
            "lat": 121.537,
            "lng": 31.258
        }
    }
)

# 輸出
{
    "acknowledged" : true,
    "insertedId" : ObjectId("61b5d4963d2fc20a8483df1a")
}      
在執行此 insertOne 方法之前,需要保證未建立 spots 集合。

通過執行這個示例 ​

​insertOne()​

​​ 方法,它不僅會将文檔插入到集合中,還會自動建立集合。該操作的輸出将通知您它已成功執行,并提供它為新文檔自動生成的 ObjectId:​

​61b5d4963d2fc20a8483df1a​

在 MongoDB 中,集合中的每個文檔都必須有一個唯一的 ​

​_id​

​​ 字段作為主鍵,是以 ​

​_id​

​​ 字段是唯一的。如果新文檔插入時為設定 ​

​_id​

​​ 字段,MongoDB 将自動生成一個對象辨別符(以 ObjectId 對象的形式)作為 ​

​_id​

​ 字段的值。

在文檔建立後,可以通過下面指令檢查 spots 集合中的對象計數來驗證文檔是否已插入:

> db.spots.count()

# 輸出:
1      

insertMany

如果需要建立多個文檔,如果通過 ​

​insertOne​

​​ 方法一個一個地插入文檔,會變的非常麻煩。是以, MongoDB 提供了 ​

​insertMany​

​ 方法,您可以使用該方法在單個操作中插入多個文檔。

運作以下示例指令,該指令使用 ​

​insertMany​

​ 方法将新的景點資訊插入 spots 集合中:

db.spots.insertMany([
  {"name": "故宮", "city": "北京", "country": "中國", "gps": { "lat": 116.403, "lng": 39.924 }},
  {"name": "長城", "city": "北京", "country": "中國", "gps": { "lat": 106.384, "lng": 39.031 }},
  {"name": "白宮", "city": "華盛頓", "country": "美國", "gps": { "lat": 116.652, "lng": 40.121 }},
  {"name": "倫敦之眼", "city": "倫敦", "country": "英國", "gps": { "lat": 116.348, "lng": 34.430 }}
])      

請注意圍繞六個文檔的方括号 ​

​([ ])​

​,這些括号表示文檔數組。在方括号内,多個對象可以一個接一個出現,以逗号分隔。在 MongoDB 方法需要多個對象的情況下,可以像這樣以數組的形式提供對象清單。

MongoDB 将響應多個對象辨別符,每個新插入的對象一個:

# 輸出
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("61b5d7ba3d2fc20a8483df1b"),
                ObjectId("61b5d7ba3d2fc20a8483df1c"),
                ObjectId("61b5d7ba3d2fc20a8483df1d"),
                ObjectId("61b5d7ba3d2fc20a8483df1e")
        ]
}      

您可以通過檢查 spots 集合中的對象個數,來驗證文檔是否已插入:

> db.spots.count()
# 輸出:
5      

查詢文檔

通過建立操作,spots 集合中存儲了一些文檔,可以查詢資料庫以檢索這些文檔并讀取它們的資料。此步驟首先概述如何查詢給定集合中的所有文檔,然後描述如何使用過濾器縮小檢索到的文檔清單。

find

完成上一步後,可以使用 ​

​find()​

​ 方法通過單個操作檢索所有文檔:

> db.spots.find()

# 輸出:
{ "_id" : ObjectId("61b5d4963d2fc20a8483df1a"), "name" : "東方明珠", "country" : "中國", "city" : "上海", "location" : { "lat" : 121.537, "lng" : 31.258 } }
{ "_id" : ObjectId("61b5d7ba3d2fc20a8483df1b"), "name" : "故宮", "city" : "北京", "country" : "中國", "gps" : { "lat" : 116.403, "lng" : 39.924 } }
{ "_id" : ObjectId("61b5d7ba3d2fc20a8483df1c"), "name" : "長城", "city" : "北京", "country" : "中國", "gps" : { "lat" : 106.384, "lng" : 39.031 } }
{ "_id" : ObjectId("61b5d7ba3d2fc20a8483df1d"), "name" : "白宮", "city" : "華盛頓", "country" : "美國", "gps" : { "lat" : 116.652, "lng" : 40.121 } }
{ "_id" : ObjectId("61b5d7ba3d2fc20a8483df1e"), "name" : "倫敦之眼", "city" : "倫敦", "country" : "英國", "gps" : { "lat" : 116.348, "lng" : 34.43 } }      

此方法在不帶任何參數的情況下使用時,不應用任何過濾并要求 MongoDB 傳回指定集合中可用的所有對象: spots。

需要注意,這些對象中的每一個都有一個您未定義的 _id 屬性。如前所述,_id 字段用作它們各自文檔的主鍵,并且是在上一步中運作 insertMany 方法時自動建立的。

為了使 find() 方法的輸出更具可讀性,您可以使用其 ​

​pretty​

​ 方法列印功能,如下所示:

db.spots.find().pretty()

# 輸出:
{
        "_id" : ObjectId("61b5d4963d2fc20a8483df1a"),
        "name" : "東方明珠",
        "country" : "中國",
        "city" : "上海",
        "location" : {
                "lat" : 121.537,
                "lng" : 31.258
        }
}
{
        "_id" : ObjectId("61b5d7ba3d2fc20a8483df1b"),
        "name" : "故宮",
        "city" : "北京",
        "country" : "中國",
        "gps" : {
                "lat" : 116.403,
                "lng" : 39.924
        }
}      
以下 find() 方法通過接受查詢過濾器文檔作為參數來傳回單個對象。查詢過濾器文檔遵循與插入到集合中的文檔相同的結構,由字段和值組成,但它們用于過濾查詢結果。

使用的查詢過濾器文檔包括 _id 字段,以對象辨別符作為值,查詢指定的對象:

```shell
db.spots.find({"_id": ObjectId("61b5d4963d2fc20a8483df1a")}).pretty()

# 輸出:
{
        "_id" : ObjectId("61b5d4963d2fc20a8483df1a"),
        "name" : "東方明珠",
        "country" : "中國",
        "city" : "上海",
        "location" : {
                "lat" : 121.537,
                "lng" : 31.258
        }
}      

也可以在文檔中通過其他字段,進行有效過濾:

db.spots.find({"country": "中國"}).pretty()

# 輸出:
{
        "_id" : ObjectId("61b5d4963d2fc20a8483df1a"),
        "name" : "東方明珠",
        "country" : "中國",
        "city" : "上海",
        "location" : {
                "lat" : 121.537,
                "lng" : 31.258
        }
}
{
        "_id" : ObjectId("61b5d7ba3d2fc20a8483df1b"),
        "name" : "故宮",
        "city" : "北京",
        "country" : "中國",
        "gps" : {
                "lat" : 116.403,
                "lng" : 39.924
        }
}
{
        "_id" : ObjectId("61b5d7ba3d2fc20a8483df1c"),
        "name" : "長城",
        "city" : "北京",
        "country" : "中國",
        "gps" : {
                "lat" : 106.384,
                "lng" : 39.031
        }
}      

查詢過濾器文檔非常強大和靈活,能夠幫助我們高效的查詢資料。

總結