gpt4 book ai didi

mongodb - MongoDB 聚合框架 $group 可以返回一个值数组吗?

转载 作者:IT老高 更新时间:2023-10-28 13:09:19 25 4
gpt4 key购买 nike

MongoDB 中用于输出格式化的聚合函数有多灵活?

数据格式:

{
"_id" : ObjectId("506ddd1900a47d802702a904"),
"port_name" : "CL1-A",
"metric" : "772.0",
"port_number" : "0",
"datetime" : ISODate("2012-10-03T14:03:00Z"),
"array_serial" : "12345"
}

现在我正在使用这个聚合函数来返回一个 DateTime 数组、一个指标数组和一个计数:

{$match : { 'array_serial' : array, 
'port_name' : { $in : ports},
'datetime' : { $gte : from, $lte : to}
}
},
{$project : { port_name : 1, metric : 1, datetime: 1}},
{$group : { _id : "$port_name",
datetime : { $push : "$datetime"},
metric : { $push : "$metric"},
count : { $sum : 1}}}

这很好,而且非常快,但是有没有办法格式化输出,以便每个日期时间/指标有一个数组?像这样:

[
{
"_id" : "portname",
"data" : [
["2012-10-01T00:00:00.000Z", 1421.01],
["2012-10-01T00:01:00.000Z", 1361.01],
["2012-10-01T00:02:00.000Z", 1221.01]
]
}
]

这将大大简化前端,因为这是图表代码所期望的格式。

最佳答案

使用聚合框架将两个字段组合成一个值数组是可能的,但绝对不是那么简单(至少在 MongoDB 2.2.0 中是这样)。

这是一个例子:

db.metrics.aggregate(

// Find matching documents first (can take advantage of index)
{ $match : {
'array_serial' : array,
'port_name' : { $in : ports},
'datetime' : { $gte : from, $lte : to}
}},

// Project desired fields and add an extra $index for # of array elements
{ $project: {
port_name: 1,
datetime: 1,
metric: 1,
index: { $const:[0,1] }
}},

// Split into document stream based on $index
{ $unwind: '$index' },

// Re-group data using conditional to create array [$datetime, $metric]
{ $group: {
_id: { id: '$_id', port_name: '$port_name' },
data: {
$push: { $cond:[ {$eq:['$index', 0]}, '$datetime', '$metric'] }
},
}},

// Sort results
{ $sort: { _id:1 } },

// Final group by port_name with data array and count
{ $group: {
_id: '$_id.port_name',
data: { $push: '$data' },
count: { $sum: 1 }
}}
)

关于mongodb - MongoDB 聚合框架 $group 可以返回一个值数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12786686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com