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

396次阅读
没有评论

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

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:MongoDB2022-12-06发表,共计397字。
新手QQ群:570568346,欢迎进群讨论 Python51学习