如何在 MongoDB 中刪除集合中的文件?
要從 MongoDB 集合中刪除文件,您需要使用 remove() 方法。語法如下
db.yourCollectionName.remove(yourDeleteValue);
在這裡,讓我們建立一個包含一些文件的集合。查詢如下
>db.deleteDocuments.insert({"UserId":1,"UserName":"Bob","UserTechnicalSubject":"Introducti on to PL/SQL"});
WriteResult({ "nInserted" : 1 })
>db.deleteDocuments.insert({"UserId":2,"UserName":"Carol","UserTechnicalSubject":"Introduction to MongoDB"});
WriteResult({ "nInserted" : 1 })
>db.deleteDocuments.insert({"UserId":3,"UserName":"John","UserTechnicalSubject":"Introduction to MySQL"});
WriteResult({ "nInserted" : 1 })
>db.deleteDocuments.insert({"UserId":4,"UserName":"Maxwell","UserTechnicalSubject":"Introduction to SQL Server"});
WriteResult({ "nInserted" : 1 })您可以使用 find() 命令顯示我們上面建立的集合中的所有文件。查詢如下
> db.deleteDocuments.find().pretty();
以下是輸出
{
"_id" : ObjectId("5c6aaa9e64f3d70fcc9147ff"),
"UserId" : 1,
"UserName" : "Bob",
"UserTechnicalSubject" : "Introduction to PL/SQL"
}
{
"_id" : ObjectId("5c6aaab464f3d70fcc914800"),
"UserId" : 2,
"UserName" : "Carol",
"UserTechnicalSubject" : "Introduction to MongoDB"
}
{
"_id" : ObjectId("5c6aaac764f3d70fcc914801"),
"UserId" : 3,
"UserName" : "John",
"UserTechnicalSubject" : "Introduction to MySQL"
}
{
"_id" : ObjectId("5c6aaadc64f3d70fcc914802"),
"UserId" : 4,
"UserName" : "Maxwell",
"UserTechnicalSubject" : "Introduction to SQL Server"
}刪除單個文件
要從集合中刪除單個文件,您需要使用 remove() 方法。查詢如下。假設我們要刪除“UserId:4”的文件
>db.deleteDocuments.remove({"UserId":4,"UserName":"Maxwell","UserTechnicalSubject":"Int
roduction to SQL Server"});
WriteResult({ "nRemoved" : 2 })現在,您可以使用 find() 命令顯示所有文件,以驗證“UserId:4”文件是否已成功刪除。查詢如下
> db.deleteDocuments.find().pretty();
以下是輸出
{
"_id" : ObjectId("5c6aaa9e64f3d70fcc9147ff"),
"UserId" : 1,
"UserName" : "Bob",
"UserTechnicalSubject" : "Introduction to PL/SQL"
}
{
"_id" : ObjectId("5c6aaab464f3d70fcc914800"),
"UserId" : 2,
"UserName" : "Carol",
"UserTechnicalSubject" : "Introduction to MongoDB"
}
{
"_id" : ObjectId("5c6aaac764f3d70fcc914801"),
"UserId" : 3,
"UserName" : "John",
"UserTechnicalSubject" : "Introduction to MySQL"
}刪除所有文件
要刪除所有文件,您需要使用以下語法
db.yourCollectionName.remove({ });查詢如下
> db.deleteDocuments.remove({});以下是輸出
WriteResult({ "nRemoved" : 3 })我們已從“deleteDocuments”集合中刪除了所有文件
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP