skip to Main Content

I have documents in a collection with date format

updated: 2022-10-25T05:04:47.904+00:00

How to modify the query to get the count for today’s date

const today = new Date()
....
await db.collection('posts').countDocuments({"updated": today})

2

Answers


  1. Chosen as BEST ANSWER

    This works but not sure if its the best way. Seems complicated for a simple task to match date.

    So set hours to 0000 and then check for documents greater than that. So everyday, new Date() will be today and this will only show documents from today.

    const today = new Date();
    today.setHours(0,0,0,0);
    const query = { "updated": { $gte: today } };
    ..
    await db.collection('posts').countDocuments(query)
    

  2. With MongoDB v5.0+,

    Use $dateTrunc with unit: "day" to perform date-only comparison.(i.e. without time part). You can use built-in $$NOW variable to get today’s date.

    db.collection.find({
      $expr: {
        $eq: [
          {
            $dateTrunc: {
              date: "$updated",
              unit: "day"
            }
          },
          {
            $dateTrunc: {
              date: "$$NOW",
              unit: "day"
            }
          }
        ]
      }
    })
    

    Mongo Playground


    With MongoDB v4.0+,

    you can rely on comparing 2 integer division result of updated and $$NOW to get today’s record.

    db.collection.find({
      $expr: {
        $eq: [
          {
            $toInt: {
              $divide: [
                {
                  $toLong: "$updated"
                },
                86400000
              ]
            }
          },
          {
            $toInt: {
              $divide: [
                {
                  $toLong: "$$NOW"
                },
                86400000
              ]
            }
          }
        ]
      }
    })
    

    Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search