gpt4 book ai didi

mongodb聚合转换为int

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

我在使用聚合框架时遇到以下问题。假设和项目以秒为单位,t 和发生的事件 id,e,如:项目:{t:11433, e:some_id}

我想要的是根据t和e进行聚合。这意味着在时间 t 内计算 id 'e' 的数量。使用 $group 的聚合很容易做到这一点。

但是,我希望有不同的时间类(class)。例如,我想计算一个时间段中相同事件 id 的数量,例如。 5秒。我可以在 js 或 python 中以编程方式执行此操作。我只是想知道它是否可以只使用 mongo,使用级联组。

我尝试使用 $divide[t,10] 进行投影。对于 11433,这将给出 1143.3 但似乎我无法删除 Mongo 中的 0.3(否则我可以按其他比例分组)。

有什么提示吗?

谢谢

最佳答案

要获得 5 秒间隔的整数组键,您可以使用公式

t = t - (t % 5)  // % is the modula operator

在聚合框架中,它看起来像这样:

db.xx.aggregate([
// you need two projections, as they can not be nested
// this does not work:
// { $project: { _id: 0, e: 1, t: 1, tk: { $subtract: [ "$t", $mod: [ "$t", 5 ] ] } } },
//
// get modula 5 of time in seconds:
{ $project: { _id: 0, e: 1, t: 1, tm5: { $mod: [ "$t", 5 ] } } },
// subtract it from time:
{ $project: { _id: 0, e: 1, ti: { $subtract: [ "$t", "$tm5" ] } } },
// now group on e and interval,
{ $group: { _id: { e: "$e", interval: "$ti" }, count: { $sum: 1 } } },
])

对于这个示例集合:

> db.xx.find()
{ "_id" : ObjectId("515e5a7157a0887a97cc8d1d"), "t" : 11433, "e" : "some_id" }
{ "_id" : ObjectId("515e60d457a0887a97cc8d1e"), "t" : 11434, "e" : "some_id" }
{ "_id" : ObjectId("515e60d857a0887a97cc8d1f"), "t" : 11438, "e" : "some_id" }

结果是:

{
"result" : [
{
"_id" : {
"e" : "some_id",
"interval" : 11435
},
"count" : 1
},
{
"_id" : {
"e" : "some_id",
"interval" : 11430
},
"count" : 2
}
],
"ok" : 1
}

关于mongodb聚合转换为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15437863/

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