Mongodb multiple date ranges -
i have collection below
{ "email" : "gg@gmail.com", "start" : isodate("2015-11-09t12:00:00.000-06:30") }, { "email" : "aa@gmail.com", "start" : isodate("2015-11-09t12:00:00.000-06:30") }, { "email" : "adjkj@gmail.com", "start" : isodate("2015-08-03t12:00:00.000-06:30") }, { "email" : "gg@gmail.com", "start" : isodate("2016-01-15t12:00:00.000-06:30") }
i want fetch emails 90 days old today's date doesn't exists in last 30 days.so in above collection below 2 documents 90 days old
{ "email" : "gg@gmail.com", "start" : isodate("2015-11-09t12:00:00.000-06:30") } { "email" : "aa@gmail.com", "start" : isodate("2015-11-09t12:00:00.000-06:30") }
however "email" : "gg@gmail.com" exists in last 30 days (see last document above), output should
{ "email" : "aa@gmail.com", "start" : isodate("2015-11-09t12:00:00.000-06:30") }
here aggregation query achieve this:
the match condition (find docs start date 90 days old
, not present in last 30 days
).
db.testing.aggregate([ {'$group': { '_id': '$email', 'start': {'$addtoset' : '$start'}}}, //consolidating docs {'$match' : { '$and': [ {'start' :{'$not': {'$gte': new date(isodate().gettime()-30*24*60*60*1000) }}}, //removing docs date exists in last 30 days. {'start' :{'$eq': new date(isodate().gettime()-90*24*60*60*1000) }} ]}} ])
i assuming want docs 90 days old. if it's document older 90 days replace $eq
$lte
.
Comments
Post a Comment