样本数据:
[
{type: 'partial', jobId: '121', browser: 'chrome', status:'true', jobName:'one'},
{type: 'partial', jobId: '122', browser: 'chrome', status:'false', jobName:'two'},
{type: 'partial', jobId: '121', browser: 'firefox', status:'false', jobName:'one'},
{type: 'partial', jobId: '122', browser: 'firefox', status:'true', jobName:'two'},
{type: 'full', jobId: '123', browser: 'chrome', status:'true', jobName:'three'},
{type: 'full', jobId: '123', browser: 'chrome', status:'true', jobName:'three'},
{type: 'full', jobId: '123', browser: 'chrome', status:'false', jobName:'three'},
{type: 'full', jobId: '124', browser: 'firefox', status:'false', jobName:'four'},
]
需要的输出:
[
{
"type": "partial",
"browsers": [
{
"browser": "chrome",
"jobIds": [
{
"jobId": "121",
"results": [
{
"jobName": "one",
"status": "true",
},
]
},
{
"jobId": "122",
"results": [
{
"jobName": "two",
"status": "false"
},
]
}
]
},
{
"browser": "firefox",
"testIds": [
{
"jobId": "121",
"results": [
{
"jobName": "one",
"status": "false"
},
]
},
{
"jobId": "122",
"results": [
{
"jobName": "two",
"status": "true"
},
]
}
]
}
]
},
{
"type": "full",
"browsers": [
{
"browser": "chrome",
"jobIds": [
{
"jobId": "123",
"results": [
{
"jobName": "three",
"status": "true"
},
{
"jobName": "three",
"status": "true"
},
{
"jobName": "three",
"status": "false"
}
]
},
]
},
{
"browser": "firefox",
"testIds": [
{
"jobId": "124",
"results": [
{
"jobName": "four",
"status": "false"
},
]
},
]
}
]
}
]
我知道如何使用分组,但是后来我不知道如何进行嵌套分组。我尝试了以下查询,但未获取所需的结果,我不知道如何继续进行。
db.collection.aggregate([
{
$match: {
jobId: {
"$exists": true
}
}
},
{
$sort: {
_id: -1
}
},
{
$group: {
_id: {
type: "$type",
browser: "$browser",
jobId: "$jobId"
},
results: {
$push: {
jobName: "$jobName",
status: "$status",
type: "$type",
jobId: "$jobId"
}
}
}
},
{
$addFields: {
results: {
$slice: [
"$results",
30
]
}
}
},
{
$group: {
_id: "$_id.browser",
results: {
$push: {
results: "$results"
}
}
}
},
])
需要获取最近的30个结果,这就是我$addFields
在查询中添加的原因。
$group
由type
,browser
并且jobId
,使results
阵列$group
通过type
和browser
,使jobs
阵列$group
通过type
并制作browsers
数组db.collection.aggregate([
{ $match: { jobId: { $exists: true } } },
{ $sort: { _id: -1 } },
{
$group: {
_id: {
type: "$type",
browser: "$browser",
jobId: "$jobId"
},
results: {
$push: {
jobName: "$jobName",
status: "$status"
}
}
}
},
{ $addFields: { results: { $slice: ["$results", 30] } } },
{
$group: {
_id: {
type: "$_id.type",
browser: "$_id.browser"
},
browser: { $first: "$_id.browser" },
jobIds: {
$push: {
jobId: "$_id.jobId",
results: "$results"
}
}
}
},
{
$group: {
_id: "$_id.type",
type: { $first: "$_id.type" },
browsers: {
$push: {
browser: "$_id.browser",
jobIds: "$jobIds"
}
}
}
},
{ $project: { _id: 0 } }
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句