Home > Mobile >  MongoDB Atlas multiple range search
MongoDB Atlas multiple range search

Time:10-25

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()

CodePudding user response:

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.

  • Related