简体   繁体   中英

Java Mongodb find filter sub array with condition

I have a mongo db collection, I want to filter only nested array

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

I use this code, I am getting the entire collection

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

I want an output filtered out the mandatory: false, only nested array needs to be filtered

This is my expected result

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

If the employee don't have any mandatory todo I still want the output as

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

I don't want to filter out the employee completely, only nested array needs to be filtered

I went through $unset $pull everything belongs to update but I want to achieve this in find

One option is to use $filter , but in case of no match it will give you [] :

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

See how it works on the playground example

If it is important to remove the field, you can add another step to it:

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

See how it works on the playground example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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