Mongodb多个日期范围

时间:2016-02-08 06:08:17

标签: mongodb date mongodb-query aggregation-framework

我有一个如下集合

{
    "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")
}

我想从今天的日期获取所有90天的电子邮件,但在过去30天内不存在。所以在上面的集合中,下面的2个文件是90天之久

{
    "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")
}

但是“电子邮件”:“gg@gmail.com”在过去30天内存在(参见上面的上一篇文章),因此输出应为

{
    "Email" : "aa@gmail.com",
    "start" : ISODate("2015-11-09T12:00:00.000-06:30")
}

1 个答案:

答案 0 :(得分:0)

以下是实现此目的的聚合查询:

匹配条件是(查找包含start date 90 days oldnot present in the 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 where the date exists in the last 30 days.
            {'start' :{'$eq':  new Date(ISODate().getTime()-90*24*60*60*1000) }}
        ]}}
])

我假设你想要的文件正好是90天。如果文档超过90天,只需将$eq替换为$lte

相关问题