要删除空字段,请使用deleteMany()
。首先让我们创建一个包含文档的集合-
> db.removeEmptyFieldsDemo.insertOne({"StudentName":""}); { "acknowledged" : true, "insertedId" : ObjectId("5ce92b9578f00858fb12e919") } > db.removeEmptyFieldsDemo.insertOne({"StudentName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce92b9878f00858fb12e91a") } > db.removeEmptyFieldsDemo.insertOne({"StudentName":""}); { "acknowledged" : true, "insertedId" : ObjectId("5ce92b9c78f00858fb12e91b") } > db.removeEmptyFieldsDemo.insertOne({"StudentName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce92ba078f00858fb12e91c") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.removeEmptyFieldsDemo.find();
这将产生以下输出-
{ "_id" : ObjectId("5ce92b9578f00858fb12e919"), "StudentName" : "" } { "_id" : ObjectId("5ce92b9878f00858fb12e91a"), "StudentName" : "Chris" } { "_id" : ObjectId("5ce92b9c78f00858fb12e91b"), "StudentName" : "" } { "_id" : ObjectId("5ce92ba078f00858fb12e91c"), "StudentName" : "Robert" }
以下是从MongoDB中删除空白字段的查询-
> db.removeEmptyFieldsDemo.updateMany({"StudentName": ""}, { $unset : {"StudentName" : 1 }}); { "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
让我们再次检查文档-
> db.removeEmptyFieldsDemo.find();
这将产生以下输出-
{ "_id" : ObjectId("5ce92b9578f00858fb12e919") } { "_id" : ObjectId("5ce92b9878f00858fb12e91a"), "StudentName" : "Chris" } { "_id" : ObjectId("5ce92b9c78f00858fb12e91b") } { "_id" : ObjectId("5ce92ba078f00858fb12e91c"), "StudentName" : "Robert" }