【问题标题】:How to check if a field is null in array of documents如何检查文档数组中的字段是否为空
【发布时间】:2022-11-02 21:00:22
【问题描述】:
{
    school:[
        {
            student:"raj",
            subjects:["P","C","M"],
            std:10
        },
        {
            student:"ram",
            subjects:[],
            std:8
        },
        {
            student:"rahul",
            subjects:["P"],
            std:9
        }
    ]
}

我想要这个没有'std'的输出,如果它为空,我不想要主题数组请帮忙

{
    school:[
        {
            student:"raj",
            subjects:["P","C","M"]
        },
        {
            student:"ram",
        },
        {
            student:"rahul",
            subjects:["P"]
        }
    ]
}

请帮助我认为可以使用地图,但无法形成 mongodb 查询

【问题讨论】:

    标签: mongodb aggregate-functions


    【解决方案1】:

    如果您只想删除一个字段,例如 std 字段,您可以使用带有投影选项的简单查询,如下所示:

    db.collection.find({},
    {
      "schoo.std": 0
    })
    

    Mongo Playground

    但是,因为您想做一个“条件投影”,即只显示一个字段,如果它不是“null”(或您的示例显示的空数组),这将需要您使用聚合框架,因为它需要一些更强大的结构操作,这是我使用 $map 运算符的方法:

    db.collection.aggregate([
      {
        $project: {
          school: {
            $map: {
              input: "$school",
              in: {
                student: "$$this.student",
                subjects: {
                  $cond: [
                    {
                      $eq: [
                        0,
                        {
                          $size: {
                            $ifNull: [
                              "$$this.subjects",
                              []
                            ]
                          }
                        }
                      ]
                    },
                    "$$REMOVE",
                    "$$this.subjects"
                  ]
                }
              }
            }
          }
        }
      }
    ])
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 2015-12-28
      • 2012-12-06
      • 2012-12-29
      • 1970-01-01
      • 2015-11-27
      • 1970-01-01
      相关资源
      最近更新 更多