简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM