[英]How to calculate an avarage time value of all selected datasets?
There are multiple documents in my db with this structure:我的数据库中有多个具有这种结构的文档:
{
"_id" : ObjectId("5d7f6a937563a63c1d8b4639"),
"admission" : ISODate("2019-09-16T10:27:20.197Z"),
"target" : [
{
"score" : 3
},
{
"score" : 2
}
],
"contact" : {
"user" : "user",
"time" : ISODate("2019-09-16T10:47:20.197Z")
}
}
I need to select all datasets with the score
of 3 as a first element of target
and return the average time difference between admission
and contact.time
.我需要score
作为target
的第一个元素的所有数据集,并返回admission
和contact.time
之间的平均时间差。
So the result should be something like: 342 datasets with score of 3 have an average time difference of 25.34 minutes所以结果应该是这样的: 342个得分为3的数据集的平均时间差为25.34分钟
So the first part should be easy by doing所以第一部分应该很容易做
db.data.find({ 'target.0': 2 })
But how do I get the avarage time difference from all these selected datasets?但是如何从所有这些选定的数据集中获得平均时间差?
You can use Aggregation Pipeline to do this.您可以使用聚合管道来执行此操作。 Based on your data format, you need target.0.score
instead of target.0
根据您的数据格式,您需要target.0.score
而不是target.0
db.data.aggregate([
{
$match : {"target.0.score": 3} // Filter All targets
},
{
$group : {
"_id" : null,
"Datasets" : {$sum : 1},
"Average" : {"$avg" : {$divide: [{$subtract: ["$contact.time", "$admission"]}, 60000]}} // Calculate Average from distance, also, Divide by 60000 to convert from milliseconds to seconds.
}
}
])
The result document will be as follows:结果文件如下:
{
"_id" : null,
"Datasets" : 3.0,
"Average" : 26.6666666666667
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.