MongoDB 學習筆記 – MongoDB Shell:CRUD 中的 Delete、Update

MongoDB 學習筆記 - MongoDB Shell:CRUD 中的 Delete、Update
MongoDB 學習筆記 - MongoDB Shell:CRUD 中的 Delete、Update

本篇要解決的問題

上一篇,我們學習了 MongoDB Shell 的 find,來查詢資料,有了 find 的基礎,會發現這一篇的 delete、update,命令很相像,基本上把 find 換成 update 就可以了。


deleteOne 刪除單一 document

db.<Collection名稱>.deleteOne(指定條件)

db.books.deleteOne({ _id: ObjectId('65bba54cee4e5a09b7d87f3f') })

成功的話會顯示以下訊息:

{
  acknowledged: true,
  deletedCount: 1
}

deleteMany 刪除多個 documents

db.<Collection名稱>.deleteMany(指定條件)

db.books.deleteMany({ rating: { $gte: 8 } })

成功的話會顯示以下訊息:

{
  acknowledged: true,
  deletedCount: 2
}

updateOne 更新單一 document

$set 更新值

db.<Collection名稱>.updateOne(指定條件, { $set: { 字段: 值, ... } })

db.books.updateOne(
    { _id: ObjectId('65bba54cee4e5a09b7d87f3f') },
    {
        $set: {
            rating: 10,
            pages: 1000
        }
    }
)

成功的話會顯示以下訊息:

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

$inc 增加、減少原有的值

比方原本我們的 pages 是 500,當執行了以下:

db.books.updateOne(
    { _id: ObjectId('65bba54cee4e5a09b7d87f3f') },
    { $inc: { pages: 10 } }
)

pages 就會是 +10,變成 510。

如果改寫成:

{ $inc: { pages: -10 } }

pages 就會是 -10,變成 490。

$pull 刪除陣列裡的值

比方原本我們的 genres 是 ["aaa", "bbb"],當執行了以下:

db.books.updateOne(
    { _id: ObjectId('65bba54cee4e5a09b7d87f3f') },
    { $pull: { genres: "aaa" } }
)

genres 的值就會變成 ["bbb"]

$push 增加陣列裡的值

比方原本我們的 genres 是 ["aaa", "bbb"],當執行了以下:

db.books.updateOne(
    { _id: ObjectId('65bba54cee4e5a09b7d87f3f') },
    { $push: { genres: "ccc" } }
)

genres 的值就會變成 ["aaa", "bbb", "ccc"]

以上是一次只增加一個值到陣列,如果想一次增加多個值,就用 $each

db.books.updateOne(
    { _id: ObjectId('65bba54cee4e5a09b7d87f3f') },
    {
        $push: {
            genres: {
                $each: ["ddd", "eee", "fff"]
            }
        }
    }
)

updateMany 更新多個 documents

db.<Collection名稱>.updateMany(指定條件, { $set: { 字段: 值, ... } })

db.books.updateMany(
    { author: "August" },
    {
        $set: {
            rating: 10,
            pages: 1000
        }
    }
)

成功的話會顯示以下訊息:

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 2,
  modifiedCount: 2,
  upsertedCount: 0
}
Summary
MongoDB 學習筆記 - MongoDB Shell:CRUD 中的 Delete、Update
Article Name
MongoDB 學習筆記 - MongoDB Shell:CRUD 中的 Delete、Update
Description
掌握 MongoDB Shell 中 的Delete 和 Update 操作。從刪除單一或多個 documents 到更新字段值,增加或減少數值,以及操作陣列,本筆記文涵蓋實際操作示例。
August
Let's Write
Let's Write
https://letswritetw.github.io/letswritetw/dist/img/logo_512.png
訂閱
通知
guest

0 Comments
最舊
最新
Inline Feedbacks
看所有留言