如何从 MongoDB 文档中彻底移除一个字段?
你可以使用 $unset 运算符从 MongoDb 文档中彻底移除一个字段。语法如下
db.yourCollectionName.update({}, {$unset: {yourFieldName:1}}, false, true);
为了理解以上语法,让我们创建一个包含某些文档的集合。创建包含文档的集合的查询如下
> db.removeFieldCompletlyDemo.insertOne({"StudentName":"Larry","StudentFavouriteSubject": ["Java","C","C++","Python"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef55a6fd07954a48906a3") } > db.removeFieldCompletlyDemo.insertOne({"StudentName":"Mike","StudentFavouriteSubject": ["Javascript","HTML5","CSS3"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef57b6fd07954a48906a4") } > db.removeFieldCompletlyDemo.insertOne({"StudentName":"Sam","StudentFavouriteSubject": ["MongoDB","MySQL","SQL Server"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef59c6fd07954a48906a5") }
在集合中显示所有文档,可借助 find() 方法。查询如下
> db.removeFieldCompletlyDemo.find().pretty();
输出结果如下
{ "_id" : ObjectId("5c6ef55a6fd07954a48906a3"), "StudentName" : "Larry", "StudentFavouriteSubject" : [ "Java", "C", "C++", "Python" ] } { "_id" : ObjectId("5c6ef57b6fd07954a48906a4"), "StudentName" : "Mike", "StudentFavouriteSubject" : [ "Javascript", "HTML5", "CSS3" ] } { "_id" : ObjectId("5c6ef59c6fd07954a48906a5"), "StudentName" : "Sam", "StudentFavouriteSubject" : [ "MongoDB", "MySQL", "SQL Server" ] }
从文档中移除字段“StudentFavouriteSubject”。查询如下
> db.removeFieldCompletlyDemo.update({}, {$unset: {StudentFavouriteSubject:1}}, false, true); WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
我们已经从文档中移除了“StudentFavouriteSubject”字段。我们现在显示集合中的所有文档来验证。
查询如下
> db.removeFieldCompletlyDemo.find().pretty();
输出结果如下
{ "_id" : ObjectId("5c6ef55a6fd07954a48906a3"), "StudentName" : "Larry" } { "_id" : ObjectId("5c6ef57b6fd07954a48906a4"), "StudentName" : "Mike" } { "_id" : ObjectId("5c6ef59c6fd07954a48906a5"), "StudentName" : "Sam" }
广告