Home > front end >  MongoDB aggregation project with cond not working
MongoDB aggregation project with cond not working

Time:03-11

I'm getting "MongoServerError: Invalid $project :: caused by :: Unrecognized parameter to $cond: $if" for this code. Whats wrong with it and how do i fix it ?

       {
          $project: {
            _id: 1,
            date: 1,
            slot: 1,
            franchiseId: 1,
            status: 1,
            order: {
              $cond: {
                $if: { $gt: ['$carspa', null] },
                $then: {
                  price: '$carspa.price',
                  mode: '$carspa.mode',
                  address: '$carspa.address',
                  addOn: '$carspa.addOn',
                  service: '$carspa_service.name'
                },
                $else: {
                  $if: { $gt: ['$mechanical', null] },
                  $then: {
                   price: '$mechanical.price',
                   mode: '$mechanical.mode',
                   address: '$mechanical.address',
                   addOn: '$mechanical.addOn',
                   service: '$mechanical_service.name'
                  },
                  $else: {
                    price: '$quickhelp.price',
                    mode: '$quickhelp.mode',
                    address: '$quickhelp.address',
                    addOn: '$quickhelp.addOn',
                    service: '$quickhelp_service.name'
                  }
                },
              },
            },
          }
        }

CodePudding user response:

Try

{
      $project: {
        _id: 1,
        date: 1,
        slot: 1,
        franchiseId: 1,
        status: 1,
        order: {
          $cond: {
            if: { $gt: ['$carspa', null] },
            then: {
              price: '$carspa.price',
              mode: '$carspa.mode',
              address: '$carspa.address',
              addOn: '$carspa.addOn',
              service: '$carspa_service.name'
            },
            else: {
              if: { $gt: ['$mechanical', null] },
              then: {
               price: '$mechanical.price',
               mode: '$mechanical.mode',
               address: '$mechanical.address',
               addOn: '$mechanical.addOn',
               service: '$mechanical_service.name'
              },
              else: {
                price: '$quickhelp.price',
                mode: '$quickhelp.mode',
                address: '$quickhelp.address',
                addOn: '$quickhelp.addOn',
                service: '$quickhelp_service.name'
              }
            },
          },
        },
      }
    }
  • Related