gpt4 book ai didi

PHP/MongoDB 使用聚合计算数组中的字符串

转载 作者:可可西里 更新时间:2023-11-01 09:52:42 26 4
gpt4 key购买 nike

我从小就使用 MySQL,现在由于各种原因不得不切换到 MongoDB。

我写了一个日志,将每个 php 错误保存在 MongoDB 集合中。读出错误不是问题,使用简单的 find() 非常简单,而且您可以使用 php 数组来获取数据真是太好了。

现在我想要一些关于错误的统计数据。我的收藏看起来像这样:

 {
"_id": ObjectId("51af10ca0e5e723c0a000000"),
"Errors": {
"2048": {
"0": {
"Message": "Declaration of ADODB_mysqli::MetaIndexes() should be compatible with ADOConnection::MetaIndexes($table, $primary = false, $owner = false)",
"File": "File.php",
"Line": NumberInt(29),
"Time": NumberInt(1370427591)
}
},
"2": {
"0": {
"Message": "Error",
"File": "File.php",
"Line": NumberInt(29),
"Time": NumberInt(1370427591)
},
"1": {
"Message": "Error",
"File": "File.php",
"Line": NumberInt(29),
"Time": NumberInt(1370427591)
}
},
"8": {
"0": {
"Message": "Undefined index: PluginLastAdded",
"File": "File.php",
"Line": NumberInt(36),
"Time": NumberInt(1370427594)
},
"1": {
"Message": "Undefined index: PluginLastAdded",
"File": "File.php",
"Line": NumberInt(36),
"Time": NumberInt(1370427594)
}
}
}
}

现在我想知道这个条目中的每个错误发生的频率。最好有一个单独的列表,分为 2048、2、8,然后是每个错误的计数。

没有太多 php 代码但使用 MongoDB 的聚合是否可能?

任何帮助都会很棒,在我看来 MongoDB 与 MySQL 有 180° 的不同,而且转换非常困难。

最佳答案

要建立在上面提到的 Sammaye 之上,以下具有真实数组的模式会更合适:

{
"_id": ObjectId("51af10ca0e5e723c0a000000"),
"errors": [
{
"code": 2048,
"message": "Declaration of ADODB_mysqli::MetaIndexes() should be compatible with ADOConnection::MetaIndexes($table, $primary = false, $owner = false)",
"file": "File.php",
"line": NumberInt(29),
"time": NumberInt(1370427591)
},
{
"code": 2,
"message": "Error",
"file": "File.php",
"line": NumberInt(29),
"time": NumberInt(1370427591)
},
{
"code": 2,
"message": "Error",
"file": "File.php",
"line": NumberInt(29),
"time": NumberInt(1370427591)
},
{
"code": 8,
"message": "Undefined index: PluginLastAdded",
"file": "File.php",
"line": NumberInt(36),
"time": NumberInt(1370427594)
},
{
"code": 8,
"message": "Undefined index: PluginLastAdded",
"file": "File.php",
"line": NumberInt(36),
"time": NumberInt(1370427594)
}
]
}

数组结构还使索引和查询更加直接。索引能够索引array values , MongoDB 也使得对数组的查询变得容易。例如,您可以灵活地使用 $elemMatch 查询特定错误(可能是代码和文件的组合)。 .此外,由于 errors 是一个真正的数组,您可以使用各种 update operators ,例如 $push$pull

需要考虑的一件事是嵌套对象限制了索引和编写查询的方式。在您之前的示例中,查询第一条错误消息的唯一方法是通过 Errors.2048.0.Message,但使用上面的架构将允许查询 errors.message.

数组也使得 Aggregation Framework对您来说是一个可行的选择,特别是因为它允许您使用其 $unwind 运算符遍历数组,然后对数组元素中的值进行 $group。除了有关聚合框架的 MongoDB 文档外,您还可以找到 this presentation有帮助,直观地了解不同的运算符。

对于您之前关于获取每个代码错误数的问题,以下聚合框架管道将计算整个集合中所有文档的错误数:

db.foo.aggregate([
{ $unwind: "$errors" },
{ $group: {
_id: "$errors.code",
num: { $sum: 1 }
}}
]);

最后,我建议将 time 字段存储为 BSON 日期(PHP 中的 MongoDate)而不是整数。这打开了使用 date operators 的选项。在聚合框架中。

关于PHP/MongoDB 使用聚合计算数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16962063/

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