从 MongoDB 中移除空字段
要移除空字段,请使用 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" }
广告