繁体   English   中英

Java Mongodb 找到符合条件的过滤器子数组

[英]Java Mongodb find filter sub array with condition

我有一个 mongo 数据库集合,我只想过滤嵌套数组

{
    "_id" : "E00001",
    "name" : "Ramu",
    "totoList" : [
        {
            "mandatory" : false,
            "description" : "call customer care"
        },
        {
            "mandatory" : true,
            "description" : "get bill from person"
        }
    ]
}

我使用这段代码,我得到了整个集合

List<Employee> empList = mongoTemplate.find(query, Employee.class);

我想要一个 output 过滤掉 mandatory: false,只需要过滤嵌套数组

这是我的预期结果

{
    "_id" : "E00001",
    "name" : "Ramu",
    "totoList" : [
        {
            "mandatory" : true,
            "description" : "get bill from person"
        }
    ]
}

如果员工没有任何强制性待办事项,我仍然希望 output 作为

{
    "_id" : "E00001",
    "name" : "Ramu"
}

我不想完全过滤掉员工,只需要过滤嵌套数组

我经历了$unset $pull everything belongs to update但我想在find中实现这个

一种选择是使用$filter ,但如果不匹配,它会给你[]

db.collection.aggregate([
  {$set: {
      totoList: {
        $filter: {
          input: "$totoList",
          cond: "$$this.mandatory"
        }
      }
  }}
])

playground 示例中查看它是如何工作的

如果删除该字段很重要,您可以为其添加另一个步骤:

  {$replaceRoot: {
      newRoot: {$cond: [
          {$gt: [{$size: "$totoList"}, 0]},
          "$$ROOT",
          {_id: "$_id", name: "$name"}
      ]}
  }}

playground 示例中查看它是如何工作的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM