yavg
yavg

Reputation: 3061

aggregation to find a document by specific date

It seems simple but I have not been able to do an aggregation that allows me to search for a document by entering a specific date.

for example I have these collections:

    {
        "_id" : ObjectId("5fbf2990846471279461d0a8"),
        "date" : ISODate("2020-11-26T04:05:36.314Z"),
    },
    {
        "_id" : ObjectId("5fbf2990846471279461d0a8"),
        "date" : ISODate("2020-11-24T04:05:36.314Z"),
    },
    {
        "_id" : ObjectId("5fbf2990846471279461d0a8"),
        "date" : ISODate("2020-11-23T04:05:36.314Z"),
    },
    {
        "_id" : ObjectId("5fbf2990846471279461d0a8"),
        "date" : ISODate("2020-11-27T04:05:36.314Z"),
    },
    {
        "_id" : ObjectId("5fbf2990846471279461d0a8"),
        "date" : ISODate("2020-11-25T04:05:36.314Z"),
    }

I want to filter the date that corresponds with 2020/11/25 (in this case it is the last collection)

what am I doing wrong?

collection.aggregate(
[
  {
    $match:  {
           "date": {
            $lte: new Date("2020/11/25"),
            $gte: new Date("2020/11/25")
           }
   }
 }
]

Desired output:

    {
        "_id" : ObjectId("5fbf2990846471279461d0a8"),
        "date" : ISODate("2020-11-25T04:05:36.314Z"),
    }

Upvotes: 1

Views: 1178

Answers (2)

turivishal
turivishal

Reputation: 36154

You can try,

  • set 0 time in start date and set end time in end date
let date = "2020/11/25";
let startDate = new Date(new Date(date).setHours(00,00,00));
let endDate = new Date(new Date(date).setHours(23,59,59,999));

db.collection.aggregate([
  {
    $match: {
      date: {
        $gte: startDate,  // ex: 2020-11-25T00:00:00.00Z
        $lte: endDate  // ex: 2020-11-25T23:59:59.00Z
      }
    }
  }
])

Playground

Upvotes: 1

varman
varman

Reputation: 8894

The problem is with the timestamp you have. So the trick what I did is, convert it to String and substring to 10.

db.collection.aggregate([
  {
    $addFields: {
      dateConverted: {
        "$dateToString": {
          "format": "%Y-%m-%d",
          "date": "$date"
        }
      }
    }
  },
  {
    $match: {
      dateConverted: {
        $gte: "2020-11-25",
        $lte: "2020-11-25"
      }
    }
  },
  {
    $project: {
      dateConverted: 0
    }
  }
])

Working Mongo playground

Upvotes: 1

Related Questions