您可以使用以下兩個步驟通過索引刪除數組元素 –
第一步如下 –
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”已被完全刪除。
以上就是如何在 MongoDB 中通過索引刪除數組元素?的詳細內容,更多請關注www.92cms.cn其它相關文章!






