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
Tried and found below ways for above question,
using aggregate([]):
db.collectionName.aggregate([{$addFields:{difference:{$subtract:[new Date(),7*24*60*60*1000]}}},{$match:{$expr:{$gte:"$createdDate","$difference"]}}}]);
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
A canonical way would be using
$dateSubtract
to compute 7 days before$$NOW
and compare the result withcreatedDaate
field.Mongo Playground