【问题标题】:Is it possible to use a MongoDB aggregate query with date matching?是否可以使用带有日期匹配的 MongoDB 聚合查询?
【发布时间】:2015-12-05 09:40:04
【问题描述】:

我正在尝试获取在某些日期分组的某些项目的计数。 这是使用以下聚合查询:

// 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 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}}
]

【问题讨论】:

  • 您正在使用“字符串”。您的文档是否包含“字符串”或它们是否包含 Date 对象。
  • @BlakesSeven 它们包含Date 对象,我只是以实际日期为例。
  • 那么你不要在不是“字符串”的东西上使用$substr。这应该很清楚。
  • 您需要将字符串包装在 ISODate() 中

标签: mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

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

因此替换这个:

'$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')

【讨论】:

    猜你喜欢
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 2019-04-15
    • 1970-01-01
    相关资源
    最近更新 更多