javascriptmongodbmongodb-querymongodb-atlas-search

MongoDB Atlas multiple range search


Is there a way to search multiple ranges for collections in mongo database?. I have tried the following but doesn't work although it works for a single range

db.collection(collection)
  .aggregate([
    {
      $search: {
        compound: {
          filter: [
            {
              range: {
                path: createdAt,
                gte: startdate,
                lte: endDate,
              },
            },
            {
              range: {
                path: updatedAt,
                gte: startdate,
                lte: endDate,
              },
            },
          ],
        },
      },
    },
    {
      $limit:20,
    },
  ])
  .toArray()

Solution

  • You may simply put a $or in $expr in the $match stage of your aggregation

    db.collection.aggregate([
      {
        "$match": {
          $expr: {
            $or: [
              {
                $and: [
                  {
                    $gte: [
                      "$createdAt",
                      startDate
                    ]
                  },
                  {
                    $lte: [
                      "$createdAt",
                      endDate
                    ]
                  }
                ]
              },
              {
                $and: [
                  {
                    $gte: [
                      "$updatedAt",
                      startDate
                    ]
                  },
                  {
                    $lte: [
                      "$updatedAt",
                      endDate
                    ]
                  }
                ]
              }
            ]
          }
        }
      }
    ])
    

    Here is the Mongo playground for your reference.