skip to Main Content

Below is a block from my aggregate query,

{
          $addFields: {
            destinations: {
              $filter: {
                input: "$destinations",
                cond: {
                  $and: [
                    {
                      $or: [
                        {
                          "$$this.reported_at": {
                            $exists: false
                          }
                        },
                        {
                          "$$this.reported_at": {
                            $eq: null
                          }
                        }
                      ],
                    },
                    {
                      $eq: [
                        "$$this.type",
                        1
                      ]
                    }
                  ]
                }
              }
            }
          }
        },

which when run is throwing the below error

query failed: (InvalidPipelineOperator) Invalid $addFields :: caused by :: Unrecognized expression '$$this.reported_at'

Although reported_at is another property just like type inside the destinations array.
When I remove the object containing the OR condition, its not throwing an error.
Please help me resolve this.

Thanks in advance

2

Answers


  1. In the $filter cond field, you have to use the expression operator. Your query should be as below:

    {
      $addFields: {
        destinations: {
          $filter: {
            input: "$destinations",
            cond: {
              $and: [
                {
                  $or: [
                    {
                      $eq: [
                        "$$this.reported_at",
                        undefined
                      ]
                    },
                    {
                      $eq: [
                        "$$this.reported_at",
                        null
                      ]
                    }
                  ],
                  
                },
                {
                  $eq: [
                    "$$this.type",
                    1
                  ]
                }
              ]
            }
          }
        }
      }
    }
    
    Login or Signup to reply.
  2. This one should also work:

    db.collection.aggregate([
       {
          $addFields: {
             destinations: {
                $filter: {
                   input: "$destinations",
                   cond: {
                      $and: [                     
                         { $in: [{ $type: "$$this.reported_at" }, ['null', 'undefined', 'missing' ]] },
                         { $eq: ["$$this.type", 1] }
                      ]
                   }
                }
             }
          }
       }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search