zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

mongodb怎么删除所有为空的字段

2023-04-18 14:23:52 时间

mongodb怎么删除所有为空的字段

1、直接使用下面的代码删除所有为空的字段:

//run in mongo shell 

var coll = db.getCollection("collectionName");
var cursor = coll.find();
while (cursor.hasNext()) {
 var doc = cursor.next();
 var keys = {};
 var hasNull = false;
 for ( var x in doc) {
 if (x!="_id" && doc[x] == null) {
 keys[x] = 1;
 hasNull = true;
 }
 }
 if (hasNull) {
 coll.update({_id: doc._id}, {$unset:keys});
 }
}

通过循环遍历所有字段获取其中为空的字段,然后使用update()方法删除所有为空的字段即可。