Mongodb - “递归"删除空字段? [英] Mongodb - remove null fields "recursively"?

查看:36
本文介绍了Mongodb - “递归"删除空字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个基于 MongoDb - 删除所有空字段的问题.引用的帖子仅提供了在顶级删除空字段的解决方案.但是,如何删除嵌入的空字段?

This is a question based on MongoDb - remove all fields that are null. The referred post only gives solution that removes null fields at the top level. However, how can I remove the null fields that embedded?

请注意,我不知道空字段的可能名称及其深度,因此我认为我们必须遍历每个文档的每个字段.

Please note that I have no idea of the possible names of the null fields and their depth, so I think we have to iterate over each field of each document.

这是一个例子:

{
    "id": 14770467,
    "f1": "a",
    "f2": null,
    "f3": [
        {
            "id": 76946819,
            "f4": null
        }
    ]
}

我期待这样的事情:

{
    "id": 14770467,
    "f1": "a",
    "f3": [
        {
            "id": 76946819
        }
    ]
}

谢谢.

推荐答案

试试这个

const remove = (data) => {
    for (let key in data) {
        const val = data[key];
        if (val == null) {
            delete data[key];
        } else if (Array.isArray(val)) {
            val.forEach((v) => {
                remove(v);
            });
        }
    }
    return data;
}


db.getCollection('Collection').find({}).forEach((data) => {
    data = remove(data);
    db.getCollection('OtherCollection').insert(data);
    //db.getCollection('Collection').save(data); // update same record
    print(data);
})

这篇关于Mongodb - “递归"删除空字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆