Remove all fields that are null

前端 未结 5 498
-上瘾入骨i
-上瘾入骨i 2021-01-02 11:03

How can I remove all fields that are null from all documents of a given collection?


I have a collection of documents such as:

{
           


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 11:45

    // 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});
        }
    }
    

提交回复
热议问题