查找存储为字符串的日期的平均差异

时间:2019-01-26 08:04:25

标签: mongodb spring-boot aggregation mongotemplate

我有一个Mongo数据库,并且已将日期存储为字符串。每个文档我都有一个名为“ creationdate”的字段和一个名为“ completiondate”的字段。日期格式为“ YYYY-MM-dd”(例如“ 2011-12-18”)。即使我可以执行诸如greatThan,GreaterThanEqual之类的简单聚合,也无法找到日期差,必须计算出日期与创建日期之间的平均天差。

上面的查询如果可能的话,我必须在Spring-boot上用MongoTemplate编写它。

我正在尝试类似的操作,但是它不起作用。

import React, { Component } from 'react'

class MenuContent extends Component {
  onLogout = () => {
    document.cookie = 'auth_token=;expires=Thu, 01 Jan 1970 00:00:01 GMT;'
  }

  render() {
    return (
      <div className="menu">
        <div onClick={this.onLogout} className="Logout">
          Click to Log Out
        </div>
        <p className="hint">
          Click outside the menu to close it, or swipe it closed on touch device
        </p>
      </div>
    )
  }
}

export default MenuContent

date1和date2均使用“ 2011-01-01”之类的字符串

2 个答案:

答案 0 :(得分:0)

这是您要寻找的吗?

db.collection.aggregate([
  {
    $project: {
      creationdate: {
        $dateFromString: {
          dateString: "$creationdate",
          format: "%Y-%m-%d"
        }
      },
      completiondate: {
        $dateFromString: {
          dateString: "$completiondate",
          format: "%Y-%m-%d"
        }
      }
    }
  },
  {
    $project: {
      difference: {
        $subtract: [
          "$completiondate",
          "$creationdate"
        ]
      }
    }
  },
  {
    $group: {
      _id: null,
      average: {
        $avg: "$difference"
      }
    }
  },
  {
    $project: {
      _id: 0,
      dayAverage: {
        $divide: [
          "$average",
          86400000
        ]
      }
    }
  }
])

我在此处创建了交互式演示:https://mongoplayground.net/p/wGRw12m3UbB

希望它会有所帮助:)

答案 1 :(得分:0)

春季启动

Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("creationdate").gte(date1).lte(date2).andOperator(Criteria.where("completiondate").ne(""))),
                Aggregation.project("servicerequesttype").and(DateOperators.DateFromString.fromStringOf("creationdate").withFormat("%Y-%m-%d")).as("creationdate").and(DateOperators.DateFromString.fromStringOf("completiondate").withFormat("%Y-%m-%d")).as("completiondate"),
                Aggregation.project("servicerequesttype").and("completiondate").minus("creationdate").as("difference"),
                Aggregation.group("servicerequesttype").first("servicerequesttype").as("servicerequesttype").avg("difference").as("temp"),
                Aggregation.project("servicerequesttype").and("temp").divide(86400000).as("average")
        );