skip to Main Content

I’d like to take weekly, hourly report of data based on date field from mongodb, for doing so, have tried to add new field called "difference" using addFields stage before the match stage and then try to use that "difference" date field in the match stage as dynamic value for the condition against the existing date field called "createdDate".

But am getting all data as output instead of expected data for only periodic dates(difference of 7 days)

sample doc from the collection:

{
"name":"Gold",
"age":20,
createdDate : ISODate("2023-05-03T12:36:02.719Z")
}

Query:

db.collectionName.aggregate([
    {$addFields:{difference:{$subtract:[new Date(),7*24*60*60*1000]}}},
    {$match:{createdDate:{$gte:"$difference"}}}
    ]);

Any suggestion pls?

2

Answers


  1. Chosen as BEST ANSWER

    Tried and found below ways for above question,

    1. using aggregate([]):

      db.collectionName.aggregate([{$addFields:{difference:{$subtract:[new Date(),7*24*60*60*1000]}}},{$match:{$expr:{$gte:"$createdDate","$difference"]}}}]);

    2. using find():

      db.collectionName.find({"createdDate":{$gt:new Date(new Date()-7*24*60*60*1000)}});

    If u feel these answers are useful please upvote


  2. A canonical way would be using $dateSubtract to compute 7 days before $$NOW and compare the result with createdDaate field.

    db.collection.find({
      "$expr": {
        "$gte": [
          "$createdDate",
          {
            "$dateSubtract": {
              "startDate": "$$NOW",
              "unit": "day",
              "amount": 7
            }
          }
        ]
      }
    })
    

    Mongo Playground

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