首页  >  文章  >  后端开发  >  Mongodb 时间序列 / Golang -

Mongodb 时间序列 / Golang -

王林
王林转载
2024-02-11 10:18:171020浏览

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 查找的类型的整个过程。time.time 类型转换为 mongodb 查找的类型的整个过程。

解决方法

您调用 Collection.InsertOne(),可用于插入单个文档。然而,devicesReadings

解决方法

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

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

以上是Mongodb 时间序列 / Golang -的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除