mongoose : How to find by date that start with a given input (like autocomplete : 25/01/2... , 25/01..)

Viewed 103

i have objects stored in db like :

[
   {
      "created_at" : ISODate("2020-03-19T07:27:32.158Z"),
   },
   {
      "created_at" : ISODate("2020-03-19T12:10:19.191Z"),
   }
]

I would like to find data by created_at (that start with) like autocomplete : 25... , 25/01... , 25/01/202...

I have an input date that i can get data in the format : 25/01/2021 : dd/mm/yyyy.

the result can be 25 or 25/0 ,

in this case i need to find data that created_at : start with 25/0

it's like the method : $regex: "^" + date but with dates

1 Answers

An example of the aggregation pipeline that uses $dateToString to convert it runtime. May be quite expensive on large collections as it processes all documents on each request and cannot use an index.

db.collection.aggregate([
  {
    "$addFields": {
      "created_at_str": {
        $dateToString: {
          date: "$created_at",
          format: "%d/%m/%Y" 
        }
      }
    }
  },
  {
    "$match": {
      "created_at_str": {
        $regex: "^" + date
      }
    }
  },
  {
    "$project": {
      "created_at_str": 0
    }
  }
])

An example to play with https://mongoplayground.net/p/zXJbsUnli3L

Related