品易云推流 关闭
文章详情页
文章 > MongoDB > mongodb怎么删除所有为空的字段

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

头像

yang

2020-05-15 09:52:193476浏览 · 0收藏 · 0评论

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

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图