Home > Enterprise >  How to aggregate on nested embedded object in MongoDB
How to aggregate on nested embedded object in MongoDB

Time:12-22

{
  "_id": 1,
  "title": {
    header1:{ "name":"A" , age:10, "active":true},
    header2:{ "name":"B" , age:15, "active":false},
    header3:{ "name":"C" , age:20, "active":true},
    header4:{ "name":"D" , age:30, "active":true},
    header5:{ "name":"E" , age:35, "active":false},
    header6:{ "name":"F" , age:40, "active":true},
    header7:{ "name":"G" , age:45, "active":false},
  }
}

How can I show only those headers whose active value is false?

CodePudding user response:

  1. $project

    1.1 Convert key-value pair to array via $objectToArray for headers field . 1.2 $filter with $$this.v.active which is false.

  2. $project

    2.1 Convert headers to key-value pair via $arrayToObject and assign to title field.

db.collection.aggregate([
  {
    $project: {
      _id: 1,
      headers: {
        $filter: {
          "input": {
            $objectToArray: "$title"
          },
          "cond": {
            "$eq": [
              "$$this.v.active",
              false
            ]
          }
        }
      }
    }
  },
  {
    $project: {
      _id: 1,
      title: {
        "$arrayToObject": "$headers"
      }
    }
  }
])

Sample Mongo Playground

  • Related