如何在MongoDB中根據索引刪除陣列元素?
您可以透過以下兩個步驟刪除陣列元素:
第一步如下:
db.yourCollectionName.update({}, {$unset : {"yourArrayFieldName.yourIndexValue" : 1 }});上述語法會在“yourIndexValue”的位置放置一個空值。之後,您需要將空值從陣列欄位中移除,從而刪除陣列元素。
第二步如下:
db.yourCollectionName.update({}, {$pull : {"yourArrayFieldName" : null}});為了實現該語法,讓我們建立一個包含文件的集合。建立包含文件的集合的查詢如下:
> db.removeArrayElementByItsIndexDemo.insertOne({"InstructorName":"David",
"InstructorAge":28,"InstructorSubject":["MongoDB","MySQL","Java","SQL Server","PL/SQL"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8abbfc6cea1f28b7aa0803")
}使用find()方法顯示集合中的所有文件。查詢如下:
> db.removeArrayElementByItsIndexDemo.find().pretty();
輸出如下:
{
"_id" : ObjectId("5c8abbfc6cea1f28b7aa0803"),
"InstructorName" : "David",
"InstructorAge" : 28,
"InstructorSubject" : [
"MongoDB",
"MySQL",
"Java",
"SQL Server",
"PL/SQL"
]
}以下是根據索引刪除陣列元素的查詢。
步驟 1 - 查詢如下:
> db.removeArrayElementByItsIndexDemo.update({}, {$unset : {"InstructorSubject.2" : 1 }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })步驟 2 - 查詢如下:
> db.removeArrayElementByItsIndexDemo.update({}, {$pull : {"InstructorSubject" : null}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })讓我們檢查陣列元素“Java”是否已被刪除。查詢如下:
> db.removeArrayElementByItsIndexDemo.find().pretty();
輸出如下:
{
"_id" : ObjectId("5c8abbfc6cea1f28b7aa0803"),
"InstructorName" : "David",
"InstructorAge" : 28,
"InstructorSubject" : [
"MongoDB",
"MySQL",
"SQL Server",
"PL/SQL"
]
}檢視示例輸出,陣列元素“Java”已被完全刪除。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP