Home > front end >  MongoDB - Use $addToSet with conditions
MongoDB - Use $addToSet with conditions

Time:06-09

In a group aggregation, I'm simply trying to add names to a set if the age is 20:

Let's say I have the following two documents:

_id: ...
timestamp: ...
name: Max
age: 20


_id: ...
timestamp: ...
name: Brian
age: 21

Now I'm trying to group these and in the $group and I'm trying to add the name of all 20 year-olds to a set:

{
  $group: {
    _id: {
      bins: {
        $dateTrunc: {
          date: '$timestamp',
          unit: 'week',
          binSize: 1
        }
      }
    },
    'NamesWithAge20': {
      $addToSet: '$name'
    }
  }
}

I'm only interested in the 'NamesWithAge20' set. In this code right now both Max and Brian are added to the set, but I want to introduce a condition that only adds the name if the age is 20. Is that possible in this stage?

CodePudding user response:

Yes you can, work with $cond and with $$REMOVE.

$$REMOVE

A variable which evaluates to the missing value. Allows for the conditional exclusion of fields. In a $project, a field set to the variable REMOVE is excluded from the output.

db.collection.aggregate([
  {
    $group: {
      _id: {
        bins: {
          $dateTrunc: {
            date: "$timestamp",
            unit: "week",
            binSize: 1
          }
        }
      },
      "NamesWithAge20": {
        $addToSet: {
          $cond: {
            if: {
              $eq: [
                "$age",
                20
              ]
            },
            then: "$name",
            else: "$$REMOVE"
          }
        }
      }
    }
  }
])

Sample Mongo Playground


If you just want to query the document with age: 20, would suggest adding $match stage to filter the documents before $group stage.

db.collection.aggregate([
  {
    $match: {
      "age": 20
    }
  },
  {
    $group: {
      _id: {
        bins: {
          $dateTrunc: {
            date: "$timestamp",
            unit: "week",
            binSize: 1
          }
        }
      },
      "NamesWithAge20": {
        $addToSet: "$name"
      }
    }
  }
])

Sample Mongo Playground ($filter)

  • Related