Skip to main content

MongoDB學習筆記 - MongoDB Shell - 搜尋語法

這裡記錄了使用 MongoDB 作為資料庫,與雲端 MongoDB Atlas 操作記錄,在 Jamstack 的時代,Mongodb 是非常普遍且主流的做法之一。

  • Shell 語法主要用於終端機的操作
  • 透過 MongoDB shell 語法去操作 MongoDB Server
  • MongoDB 版本 5.0
  • 👉 官網範例


顯示資料庫

> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB

切換資料庫

> use [資料庫名稱]
switched to db [資料庫名稱]

插入一筆/多筆資料

> db.rooms.insertOne({"rating":4.5,"price":1000,"name":"標準單人房"})
{
"acknowledged" : true,
"insertedId" : ObjectId("62452ea200215a13d32151f4")
}

使用 Compass GUI 查看本地端 DB


更新與取代

> db.rooms.updateOne(
{
"_id": ObjectId("62455ea400215a13d32151f6")
},
{ $set:
{
"name": "豪華單人房限定版",
"rating": 4.3
}
}
)
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
  • 找到並且修改一筆成功
> db.rooms.updateMany(
{
"rating": 4.3
},
{ $set:
{
"rating": 4.0
}
}
)

{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
  • 找到並且修改兩筆成功

  • replaceOne() 會取代整個資料結構,不用寫$set

> db.rooms.replaceOne(
{
"name": "標準單人房"
},
{
"name": "標準單人房升級版"
}
)

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

  • 除了 name 以外其他屬性都沒了

刪除

> db.rooms.deleteOne(
{
"_id": ObjectId("62455ea400215a13d32151f7")
}
)

{ "acknowledged" : true, "deletedCount" : 1 }
  • 刪除多筆
> db.rooms.deleteMany(
{
"rating": 4
}
)

{ "acknowledged" : true, "deletedCount" : 2 }

練習用 JSON

[
{
"rating": 4.5,
"price": 1000,
"name": "標準單人房",
"payment":["信用卡","ATM"]
},
{
"rating": 4.3,
"price": 1500,
"name": "豪華單人房",
"payment":["信用卡","ATM"]
},
{
"rating": 4.8,
"price": 2000,
"name": "標準雙人房",
"payment":["信用卡","ATM"]
},
{
"rating": 4.7,
"price": 2500,
"name": "豪華雙人房",
"payment":["ATM"]
},
{
"rating": 4.0,
"price": 3000,
"name": "標準四人房",
"payment":["現金"]
},
{
"rating": 3.5,
"price": 10000,
"name": "總統套房",
"payment":["現金"]
}
]

MongoDB 相關文章: