您现在的位置是:课程教程文章

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

2023-12-18 18:49课程教程文章 人已围观

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()方法删除所有为空的字段即可。

课程教程:mongodb怎么删除所有为空的字段

上一篇:mongodb数据怎么导入新表中?

下一篇:没有了

站点信息

  • 文章统计篇文章