MongoDB - 刪除文件



在本節中,我們將學習如何使用 MongoDB 刪除文件。

remove() 方法

MongoDB 的 remove() 方法用於從集合中刪除文件。remove() 方法接受兩個引數。一個是刪除條件,第二個是 justOne 標誌。

  • 刪除條件 − (可選)根據文件將要刪除的刪除條件。

  • justOne − (可選)如果設定為 true 或 1,則僅刪除一個文件。

語法

remove() 方法的基本語法如下所示:

>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

示例

假設 mycol 集合包含以下資料。

{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}

以下示例將刪除標題為“MongoDB 概述”的所有文件。

>db.mycol.remove({'title':'MongoDB Overview'})
WriteResult({"nRemoved" : 1})
> db.mycol.find()
{"_id" : ObjectId("507f191e810c19729de860e2"), "title" : "NoSQL Overview" }
{"_id" : ObjectId("507f191e810c19729de860e3"), "title" : "Tutorials Point Overview" }

僅刪除一個

如果有多條記錄,並且您只想刪除第一條記錄,則在 remove() 方法中設定 justOne 引數。

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

刪除所有文件

如果您未指定刪除條件,則 MongoDB 將刪除集合中的所有文件。這相當於 SQL 的 truncate 命令。

> db.mycol.remove({})
WriteResult({ "nRemoved" : 2 })
> db.mycol.find()
>
廣告

© . All rights reserved.