如何在mongodb中的相同索引处减去两个数组的元素

时间:2019-01-22 17:50:18

标签: java mongodb spring-data

我正在尝试使用春季数据查找mongodb中报告的事件的平均完成时间。

我要查找的是每个serviceRequestType的事件的平均完成时间。完成时间必须减去completeDate和creationDate。

我发生了一次收集事件,文档如下:

{
    "_id": "5c451b7ab5bd0fd4a6d9b4ba",
    "serviceRequestType": "Type A",
    "status": "Completed",
    "creationDate": "2014-01-18T00:00:00",
    "completionDate": "2014-01-21T00:00:00",
    "streetAddress": "5541 W CATALPA AVE"
}

我尝试过:

Aggregation agg = newAggregation(
  group("serviceRequestType").addToSet("creationDate").as("start")
                             .addToSet("completionDate").as("end"),
  unwind("end", "endArray"),
  unwind("start", "startArray")

AggregationResults<Query4Result> result = mongoTemplate.aggregate(agg, "incidents", Query4Result.class);

return result.getMappedResults();

但是会产生

{_id=TypeA, start=2014-04-07T00:00:00, end=2014-05-12T00:00:00, 
endArray=0, startArray=0}
{_id=TypeA, start=2014-04-06T00:00:00, end=2014-05-12T00:00:00, 
endArray=0, startArray=1}
{_id=TypeA, start=2014-04-05T00:00:00, end=2014-05-12T00:00:00, 
endArray=0, startArray=2}
{_id=TypeA, start=2014-04-07T00:00:00, end=2014-07-09T00:00:00,             
endArray=1, startArray=0}
{_id=TypeA, start=2014-04-06T00:00:00, end=2014-07-09T00:00:00,     
endArray=1, startArray=1}
{_id=TypeA, start=2014-04-05T00:00:00, end=2014-07-09T00:00:00, 
endArray=1, startArray=2}


{_id=TypeB, start=2014-04-07T00:00:00, end=2014-05-23T00:00:00, 
endArray=0, startArray=0}
{_id=TypeB, start=2014-04-06T00:00:00, end=2014-05-23T00:00:00, 
endArray=0, startArray=1}
{_id=TypeB, start=2014-04-05T00:00:00, end=2014-05-23T00:00:00, 
endArray=0, startArray=2}
{_id=TypeB, start=2014-04-07T00:00:00, end=2014-05-20T00:00:00, 
endArray=1, startArray=0}
{_id=TypeB, start=2014-04-06T00:00:00, end=2014-05-20T00:00:00, 
endArray=1, startArray=1}
{_id=TypeB, start=2014-04-05T00:00:00, end=2014-05-20T00:00:00, 
endArray=1, startArray=2}

关于每个serviceRequestType减去每个文档的完成日期和创建日期的其他想法

1 个答案:

答案 0 :(得分:0)

MongoQuery应该看起来像这样:

db.getCollection('incidents').aggregate([
    { "$group": {
        "_id": "$serviceRequestType" ,
        "totalMinutes": {
            "$sum": {
                "$divide": [
                    { "$subtract": [ {$dateFromString : {"dateString": "$completionDate"}}, {$dateFromString : {"dateString": "$creationDate"}}] },
                    1000 * 60
                ]
            }
        },
        "count": {
            $sum: 1
        }
    }},
    {$project : {"serviceRequestType" : 1, "averageTime": {$divide : ["$totalMinutes", "$count"]}}}

])

如果您的日期已经在ISODate中,则可以跳过datefromstring方法。