是否可以使用日期匹配的MongoDB聚合查询? [英] Is it possible to use a MongoDB aggregate query with date matching?

查看:73
本文介绍了是否可以使用日期匹配的MongoDB聚合查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取在某些日期分组的某些项目的计数.使用以下聚合查询可以正常工作:

Im trying to get the count of certain items grouped on certain dates. This is working using the following aggregate query:

// this query works, without matching dates
[
  {'$match': {
    'some_id': ObjectId('foobar'),
    'some_boolean_value': true
    }
  },
  {'$project':
    {'day':
      {'$substr': ['$some_date', 0, 10]}}
  },
  {'$group': {_id: '$day', count: { '$sum': 1 }}},
  {'$sort': {_id: -1}}
]

下一步是我要使用此查询,但有日期限制.我想要在某些日期限制之间每天分组的计数.

The next step is that I want to use this query but with date limits. I want the count, grouped per day, between certain date limits.

 // the query below does not work as soon as date matching is added
 // this query always return 0 documents
[
  {'$match': {
    'some_id': ObjectId('foobar'),
    'some_boolean_value': true,
    'some_date':
      {
        '$gte': '2015-08-01T00:00:00.000Z',
        '$lte': '2015-08-31T23:59:59.999Z'
      }
    }
  },
  {'$project':
    {'day':
      {'$substr': ['$some_date', 0, 10]}}
  },
  {'$group': {_id: '$day', count: { '$sum': 1 }}},
  {'$sort': {_id: -1}}
]

推荐答案

您要过滤文档并仅匹配指定日期时间窗口中的文档.但是您使用字符串比较而不是日期比较.

You want to filter documents and match only those in a specified datetime window. But you use string comparison instead of date comparison.

因此请替换为:

'$gte': '2015-08-01T00:00:00.000Z',
'$lte': '2015-08-31T23:59:59.999Z'

与此:

'$gte': new Date('2015-08-01T00:00:00.000Z'),
'$lte': new Date('2015-08-31T23:59:59.999Z')

这篇关于是否可以使用日期匹配的MongoDB聚合查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆