• 技术文章 >数据库 >MongoDB

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

    yangyang2020-05-15 09:52:19原创3285

    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可视化工具有什么? 下一篇:mongodb数据怎么导入新表中?

    相关文章推荐

    • mongodb --fork启动失败怎么解决• mongodb的key能用中文吗?• mongodb分片是什么意思?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网