javascriptmongodb

MongoDb $filter with $or not working as expected


Please open this playground and follow with me: playground

I have a collection names Pages where each document has keys Urls and DraftUrls which is an array of objects as below:

IncomingUrl: string;
EclipseId: string;
Status: string;
RedirectionLink: string;
Validity: Date;
Config: ConfigData[];
Indexing: boolean;

Now, I just want to find the count of URLs which have either a status of Inactive or have an expired Validity. Also I want a few more info like GroupName and TemplateName.

I tried to use $filter with $or as you can see in the playground but the issue is that its giving me the count of all URLs without checking for the specified conditions in cond.

At first I thought there was an issue with how the Validity is checked but then I removed that part and checked just for the Inactive state, but still it gave me count of all Urls


Solution

  • Your cond expression in the $filter is incorrect. Modify so that the $filter operator should be as below:

    {
        $addFields: {
          filteredUrls: {
            $filter: {
              input: isDraftB ? '$DraftUrls' : '$Urls',
              cond: {
                $or: [
                  {
                    $eq: [
                      "$$this.Status",
                      "Inactive"
                    ]
                  },
                  {
                    $and: [
                      {
                        $eq: [
                          "$$this.Status",
                          "Validity"
                        ]
                      },
                      {
                        $gte: [
                          "$$this.Validity",
                          currentDate
                        ]
                      }
                    ]
                  }
                ]
              }
            }
          }
        }
      },