删除MongoDB中数组字段中的所有元素?
您可以为此使用$set运算符。语法如下-
db.yourCollectionName.update({}, { $set : {"yourFieldName": [] }} , {multi:true} );
为了理解上述语法,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.deleteAllElementsInArrayDemo.insertOne({"InstructorName":"Larry","InstructorTechnicalSubject":["Java","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8fb971d3c9d04998abf00e") } > db.deleteAllElementsInArrayDemo.insertOne({"InstructorName":"Mike","InstructorTechnicalSubject":["C","C++","Python"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8fb98ad3c9d04998abf00f") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.deleteAllElementsInArrayDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c8fb971d3c9d04998abf00e"), "InstructorName" : "Larry", "InstructorTechnicalSubject" : [ "Java", "MongoDB" ] } { "_id" : ObjectId("5c8fb98ad3c9d04998abf00f"), "InstructorName" : "Mike", "InstructorTechnicalSubject" : [ "C", "C++", "Python" ] }
这是删除数组字段中所有元素的查询-
> db.deleteAllElementsInArrayDemo.update({}, { $set : {"InstructorTechnicalSubject": [] }} , {multi:true} ); WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
现在让我们使用来检查集合中的所有文档find()
。查询如下-
> db.deleteAllElementsInArrayDemo.find().pretty();
以下是输出。我们删除了“InstructorTechnicalSubject”数组字段的所有元素:
{ "_id" : ObjectId("5c8fb971d3c9d04998abf00e"), "InstructorName" : "Larry", "InstructorTechnicalSubject" : [ ] } { "_id" : ObjectId("5c8fb98ad3c9d04998abf00f"), "InstructorName" : "Mike", "InstructorTechnicalSubject" : [ ] }