根据两个文档之间的相同字段计算持续时间

时间:2018-10-10 12:19:13

标签: mongodb aggregation-framework grouping

我有很多收藏。我特别有两种收藏:1。与电子学习平台形式的内容可视化开始相对应的集合; 2.与该内容可视化结束相对应的集合。这里是开始和结束可视化集合的示例:

开始可视化:

    "statement" : {
    "actor" : {
        "objectType" : "Agent",
        "name" : "exemple1@gmail.com",
        "mbox" : "mailto:exemple1@gmail.com"
    },
    "verb" : {
        "id" : "http://adlnet.gov/expapi/verbs/launched",
        "display" : {
            "en" : "Launching the next piece of learning content",
        }
    },
    "object" : {
        "objectType" : "Activity",
        "id" : "https://exemple1.com/activities/plannode=5857",
        "definition" : {
            "name" : {
                "en" : "calculs",
            },
            "type" : "http://id.tincanapi.com/activitytype/legacy-learning-standar"
        }
    },
    "context" : {
        "platform" : "exemple",
        "language" : "en",
    },
    "timestamp" : "2017-01-16T23:45:06+01:00",
    "id" : "0d7c852d-f1bf-45be-8a25-aff286bf1c30",
    "version" : "1.0.0"
},

结束可视化:

        "statement" : {
    "actor" : {
        "objectType" : "Agent",
        "name" : "exemple1@gmail.com",
        "mbox" : "mailto:exemple1@gmail.com"
    },
    "verb" : {
        "id" : "http://adlnet.gov/expapi/verbs/terminated",
        "display" : {
            "en" : "Launching the next piece of learning content",
        }
    },
    "object" : {
        "objectType" : "Activity",
        "id" : "https://exemple1.com/activities/plannode=5857",
        "definition" : {
            "name" : {
                "en" : "calculs",
            },
            "type" : "http://id.tincanapi.com/activitytype/legacy-learning-standar"
        }
    },
    "context" : {
        "platform" : "exemple",
        "language" : "en",
    },
    "timestamp" : "2017-01-16T23:45:06+01:00",
    "id" : "0d7c852d-f1bf-45be-8a25-aff286bf1c30",
    "version" : "1.0.0"
},

现在,我要做的是按object.id对这些论文集进行分组,并计算内容可视化的持续时间=时间戳(内容结束可视化)-时间戳(内容开始可视化)。

我尝试下面的代码,但是它不起作用:

db.statements.aggregate([
{$match:{'statement.verb.id':{"$in":["http://adlnet.gov/expapi/verbs/launched", "http://adlnet.gov/expapi/verbs/terminated"]}}]},
{$group:{_id:{
        objectid: "$statement.object.id",
        learner: "$statement.actor.mbox"
        },
        duration : {$subtract: ["$timestamp", "$timestamp"}]}}
       }
     }

])

有什么可以帮助我计算这两个集合之间的持续时间的吗?(持续时间需要根据两个具有相同名称的字段进行计算:时间戳)。

1 个答案:

答案 0 :(得分:1)

您可以使用以下汇总。

db.statements.aggregate([
  {"$match":{"statement.verb.id":{"$in":["http://adlnet.gov/expapi/verbs/launched","http://adlnet.gov/expapi/verbs/terminated"]}}},
  {"$group":{
    "_id":{"objectid":"$statement.object.id","learner":"$statement.actor.mbox"},
    "first":{"$first":"$timestamp"},"second":{"$last":"$timestamp"}
  }},
  {"$addFields":{"duration":{"$abs":{"$subtract":["$first","$second"]}}}}
])