Search code examples
mongodbaggregation-frameworkconditional-statementsaggregate

Aggregation pipeline $set a value to boolean whether $and is true or false


In my aggregation pipeline, I am trying to set a value to true if several conditions are matched. I will be adding more $and conditions later, but it doesn't even work with one condition.

These are the things I have tried:

    {
      $set: {
        someValue: {
          $and: [
            {
              'ratePlans.maxAdvBookDays': {
                $gte: advBookDays,
              },
            },
          ],
        }
      }
    }
    {
      $set: {
        someValue: {
          $and: [
            {
              $toBool: {
                'ratePlans.maxAdvBookDays': {
                  $gte: advBookDays,
                },
              },
            }
          ],
        }
      }
    }
    {
      $set: {
        someValue: {
          $cond: {
            if: {
              $and: [
                {
                  'ratePlans.maxAdvBookDays': {
                    $gte: advBookDays,
                  },
                },
              ],
            },
            then: 'then',
            else: 'else',
          }
        }
      }
    }

In each case, I get the following error:

MongoServerError: Invalid $set :: caused by :: FieldPath field names may not contain '.'.

However, when hard-coding the boolean values in, it does seem to work:

    {
      $set: {
        someValue: {
          $and: [
            true, true, false, true
          ],
        }
      }
    },

Solution

  • db.collection.aggregate([
      {
        $set: {
          someValue: {
            $cond: {
              if: {
                $and: [
                  {
                    $gte: [ "$ratePlans.maxAdvBookDays", 2 ]
                  }
                ]
              },
              then: "then",
              else: "else"
            }
          }
        }
      }
    ])
    

    mongoplayground