skip to Main Content

i am trying to fetch data from mongodb using aggregate query in nodejs for a specific date range,

    let date = '20230925'
    let year = date.slice(0, 4);
    let month = String(date.slice(4, 6)).padStart(2, '0');
    let day = date.slice(6, 8);
    let startFormatedDate:any = `${year}-${month}-${day}T00:01:01.111+00:00`
    let endFormatedDate:any = `${year}-${month}-${day}T23:58:58.998+00:00`

My aggregate query is

{ $sort: { updatedAt: -1 } },
{
  $match: { $and: [ 
    { updatedAt: { $gt: startFormatedDate } },
    { updatedAt: { $lt: endFormatedDate } }
   ], },
},

with this condition i am getting data for 2023-09-25, but i am also getting data for 2023-09-26

can anyone suggest me what might be the issue

EDIT :

{
  $match: { $and: [ 
   { updatedAt: { $gt: new Date(startFormatedDate) } },
   { updatedAt: { $lt: new Date(endFormatedDate) } },
  ],},
},
{ $sort: { updatedAt: -1 } },

with updated query, i am getting same result.

2

Answers


  1. I would suggest a 3rd party Date library, e.g. Luxon. Then it would be simply:

    let date = '20230925'
    
      {
        $match: {
          updatedAt: {
            $gte: DateTime.fromISO(date).toJSDate(),
            $lte: DateTime.fromISO(date).endOf('day').toJSDate()
          }
        }
      }
    
    Login or Signup to reply.
  2. To fetch data from MongoDB using an aggregate query in Node.js for a specific date range, you can use the $match operator in combination with $gte (greater than or equal) and $lte (less than or equal) operators. Example:

    const MongoClient = require('mongodb').MongoClient;
    
    let date = '20230925'
    let year = date.slice(0, 4);
    let month = String(date.slice(4, 6)).padStart(2, '0');
    let day = date.slice(6, 8);
    let startFormatedDate = new Date(`${year}-${month}-${day}T00:01:01.111+00:00`);
    let endFormatedDate = new Date(`${year}-${month}-${day}T23:58:58.998+00:00`);
    
    MongoClient.connect('mongodb://localhost:27017', function(err, client) {
      if(err) throw err;
    
      const db = client.db('your_database_name');
      const collection = db.collection('your_collection_name');
    
      collection.aggregate([
        {
          $match: {
            date_field: {
              $gte: startFormatedDate,
              $lte: endFormatedDate
            }
          }
        }
      ]).toArray(function(err, docs) {
        if(err) throw err;
    
        console.log(docs);
        client.close();
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search