我有看起来像这样的文件
{
"_id": "5e3334cede31d9555e38dbee",
"time": 400,
"datetime": "2020-01-05T16:35:42.315Z",
"version": "2.0.30",
"hostname": "bvasilchik-lt.extron.com",
"testfile": "cards.txt",
"tests": 5,
"failures": 3,
"skips": 0,
"status": "Failed",
"__v": 0
}
我想创建一个包括每名testfile的时间最多的文件,所以,如果前10名都是相同的结果testfile的名字我只是想显示前一个有相同名称testfile的。
我已经做到了,但是我还想包含另一个字段,该字段还显示与该分组匹配的测试数量,但是我发现的唯一方法是为测试添加$ first或$ last或$ max或$ min字段,但这并不是正确的,因为最高时间可能会有不同数量的测试。
我也在匹配特定日期范围内的结果
const times = await Suite.aggregate([
{
"$match": {
datetime: { "$gte": dateRange.startDate, "$lt": dateRange.endDate, }
}
},
{
"$group": {
_id: "$testfile",
time: { "$max" : "$time" },
}
},
{
"$sort": {
time: order
}
},
{
"$project": {
_id: 0,
testfile: "$_id",
time: "$time"
}
}
])
这会产生这些结果
[
{
"testfile": "lists.txt",
"time": 900
},
{
"testfile": "buttons.txt",
"time": 800
},
{
"testfile": "cards.txt",
"time": 400
},
{
"testfile": "popover.txt",
"time": 300
},
{
"testfile": "about-pages.neb",
"time": 76
}
]
但是我想要它返回的是
[
{
"testfile": "lists.txt",
"tests": 5,
"time": 900
},
{
"testfile": "buttons.txt",
"tests": 4,
"time": 800
},
{
"testfile": "cards.txt",
"tests": 8,
"time": 400
},
{
"testfile": "popover.txt",
"tests": 1,
"time": 300
},
{
"testfile": "about-pages.neb",
"tests": 2,
"time": 76
}
]
您需要在$group
和$project
阶段添加额外的字段。
您需要$max
对time
字段使用运算符并累积tests
字段time:tests
值。在最后阶段,我们$reduce
tests
以最高的价值
{
"$group": {
_id: "$testfile",
time: {
$max: "$time"
},
tests: {
"$push": {
time: "$time",
tests: "$tests"
}
}
}
},
{
"$sort": {
time: 1
}
},
{
"$project": {
_id: 0,
testfile: "$_id",
time: "$time",
tests: {
$reduce: {
input: "$tests",
initialValue: 0,
in: {
$add: [
"$$value",
{
$cond: [
{
$and: [
{
$eq: [
"$time",
"$$this.time"
]
},
{
$gt: [
"$$this.tests",
"$$value"
]
}
]
},
{
$subtract: [
"$$this.tests",
"$$value"
]
},
0
]
}
]
}
}
}
}
}
我最初曾尝试过,但是遇到了一个问题,即时间最长的测试文件可能没有最多的测试量,原因是现在对测试进行了编辑,现在它比以前有更少或更多的测试。我想知道测试时间最长的测试文件,并且知道该测试文件中有多少测试,这是一个示例,其中包含更多数据mongoplayground.net/p/1n7v8U1UmmO测试时间为“时间”:76.404574有4个测试,但查询导致5次测试,因为那是testfile about-pages.neb拥有的最大值
@BarretV请再次检查,我已经更新了答案
我在mongoplayground mongoplayground.net/p/mhIU5lvD5lC上进行了尝试 ,它仍然显示about-pages.neb的时间为76.404574,这是正确的最高时间,但是如果您查看具有该时间的文档,则只有4用于测试,但是聚合显示的测试值为5。我想很难找到具有匹配时间的文档并从聚合中获取测试的值
@BarretV请再次检查,更新
@BarretV酷。祝好运