Home > database >  mongodb aggregate nested arrays filter not empty
mongodb aggregate nested arrays filter not empty

Time:01-05

But now I don't know how to filter
I'm aggregating the filtered data:

[
       {
            "_id": "61cea071cfa3c96b9a4d2657",
            "name": "Utils",
            "children": [
                {
                    "name": "Code",
                    "_id": "61cebb4e6c4a5c643494d1a1",
                    "children": [{name:"jahn"}]
                },
                {
                    "name": "Image",
                    "_id": "61ceb8ad6c4a5c643494d11e",
                    "children": []
                }
            ]
        },
        {
            "_id": "61cea071cfa3c96b9a4d2111",
            "name": "Names",
            "children": [
               {
                    "name": "que",
                    "_id": "61cebb4e6c4a5c643494d1a1",
                    "children": [
                       
                     ]
                },
                {
                    "name": "filter",
                    "_id": "61cebb4e6c4a5c643494d1a1",
                    "children": [
                        {name:"jahn"}
                     ]
                }
            ]
        },
]

Looking forward to your help How to filter out children when children are empty and not displayed
Desired result :

[
        {
            "_id": "61cea071cfa3c96b9a4d2657",
            "name": "Utils",
            "children": [
                {
                    "name": "Code",
                    "_id": "61cebb4e6c4a5c643494d1a1",
                    "children": [
                        {name:"jahn"}
                     ]
                }
            ]
        },
        {
            "children": [
                {
                    "children": [
                        {name:"jahn"}
                     ]
                }
            ]
        },
]

I want if children in children, if it's empty it doesn't show the whole object

CodePudding user response:

If you tried to filter for the second level children array, you can use $filter.

db.collection.aggregate([
  {
    $project: {
      _id: 1,
      name: 1,
      children: {
        "$filter": {
          "input": "$children",
          "cond": {
            "$ne": [
              "$$this.children",
              []
            ]
          }
        }
      }
    }
  }
])

Sample Mongo Playground

Note:

"$ne": [
  "$$this.children",
  []
]

Can be replaced with:

"$ne": [
  {
    $size: "$$this.children"
  },
  0
]
  •  Tags:  
  • Related