how to filter in nested arrays?

You can try,

  • $set to update array field, $map to iterate loop of array field, check condition if name is name2 then $filter to get matching value v2 documents from nestedArray field and $mergeObject merge objects with available objects
let name = "name2", value = "v2";
db.collection.aggregate([
  {
    $set: {
      array: {
        $map: {
          input: "$array",
          in: {
            $mergeObjects: [
              "$$this",
              {
                $cond: [
                  { $eq: ["$$this.name", name] }, //name add here
                  {
                    nestedArray: {
                      $filter: {
                        input: "$$this.nestedArray",
                        cond: { $eq: ["$$this.value", value] } //value add here
                      }
                    }
                  },
                  {}
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Playground

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top