Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I $addToSet with conditions in MongoDB?

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 I’m trying to add the name of all 20 year-olds to a set:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  $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 is 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?

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading