Mongo 4.2:删除空字段

问题描述

我的MongoDB集合中的文档如下:

我的Mongo版本是4.2.3

{
            "_id": "SAGE-UW-00005","carriers": [
                {
                    "bindable": true,"carrierCode": "LMICO","mapped": true,"products": [
                        {
                            "industries": [
                                {
                                    "industryCode": null,"states": "GA"
                                }
                            ],"isAllNCCIValid": null,"isAllstateValid": true,}
                    ],"questionCode": "LMGENRL17"
                }
            ],"column": 1,"dataType": null,}

这是我想要的输出

{
        "_id": "SAGE-UW-00005","carriers": [
            {
                "bindable": true,"products": [
                    {
                        "industries": [
                            {
                          
                                 "states": "GA"
                            }
                        ],}
                ],"questionCode": "LMGENRL17"
            }
        ],}

我不确定集合中嵌套子文档的深度,但是集合中应该有很多空字段。我的后端代码使用$ exists查询集合中的字段,因此null会在这里造成问题。

解决方法

我不确定集合中嵌套子文档的深度,但是集合中应该有很多空字段

这是一个动态的问题。最好的选择是在删除代码中的空字段之后替换文档。

由于您具有嵌套级别,因此建议您将数据映射到pojo,并检查是否有任何条目和字段为空。除非您知道这些字段,否则删除它们的效率不高。