首页 > 后端开发 > Golang > 正文

Mongodb 时间序列 / Golang -

王林
发布: 2024-02-11 10:18:17
转载
1277人浏览过

mongodb 时间序列 / golang -

php小编子墨为大家带来了关于"Mongodb 时间序列 / Golang -"的介绍。Mongodb是一种非关系型数据库,而Golang则是一种高效的编程语言。在时间序列数据处理方面,Mongodb和Golang的结合可以提供强大的功能和性能。本文将详细介绍如何使用Mongodb和Golang来处理时间序列数据,包括数据的存储、查询和分析等。无论你是初学者还是有一定经验的开发者,本文都会帮助你更好地理解和应用Mongodb和Golang在时间序列数据处理中的优势和技巧。

问题内容

我有以下示例 go 代码,它将来自 rest 请求 (gin) 的数据插入到 mongodb 中,但失败了:

['timestamp' must be present and contain a valid bson utc datetime value]
登录后复制

代码:

func CreateDevicesReadings(c *gin.Context) {

var devicesReadings DevicesReadings
c.BindJSON(&devicesReadings)

// Connect to MongoDB
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
    c.JSON(500, gin.H{
        "message": "Internal Server Error. Could not connect to the database.",

    })
    log.Default().Println(err)
}

collection := client.Database("florly").Collection("devicesReadings")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)


// Set timestamp to the current time at the moment of the request
for i := 0; i < len(devicesReadings.DevicesReadings); i++ {
    devicesReadings.DevicesReadings[i].Timestamp = time.Now().UTC()
} 
_, err = collection.InsertOne(ctx, devicesReadings)
if err != nil {
    c.JSON(500, gin.H{
        "message": "Internal Server Error. Could not insert the data into the database.",
    })
    log.Default().Println(err)
} else {
    log.Default().Println("Data inserted successfully.")
}

client.Disconnect(context.Background())
}

type DeviceReadings struct {
    ID      primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
    Alias          string `json:"alias" bson:"alias"`
    Timestamp   time.Time `json:"timestamp,omitempty" bson:"timestamp"`
    SystemReadings SystemReadings `json:"systemReadings" bson:"systemReadings"`
    SensorReadings SensorReadings `json:"sensorsReadings" bson:"sensorsReadings"`
}
登录后复制

我做错了什么?我认为 mongodb 完成了将 time.time 类型转换为 mongodb 查找的类型的整个过程。

序列猴子开放平台
序列猴子开放平台

具有长序列、多模态、单模型、大数据等特点的超大规模语言模型

序列猴子开放平台 0
查看详情 序列猴子开放平台

立即学习go语言免费学习笔记(深入)”;

解决方法

您调用 Collection.InsertOne(),可用于插入单个文档。然而,devicesReadings 是多个文档的一部分。

因此,您要么必须迭代所有文档并将它们单独传递给 Collection.InsertOne(),要么使用 Collection.InsertMany(),使用要插入的多个文档的切片。

以上就是Mongodb 时间序列 / Golang -的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号