首页 > 解决方案 > 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,
                "carrierCode": "LMICO",
                "mapped": true,
                "products": [
                    {
                        "industries": [
                            {
                          
                                 "states": "GA"
                            }
                        ],
      
                        "isAllstateValid": true,
                        
                    }
                ],
                "questionCode": "LMGENRL17"
            }
        ],
        "column": 1,
     
        
    }

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

标签: arraysmongodbnosqlmongo-shell

解决方案


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

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

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


推荐阅读