首頁  >  文章  >  後端開發  >  Mongodb 時間序列 / Golang -

Mongodb 時間序列 / Golang -

王林
王林轉載
2024-02-11 10:18:171018瀏覽

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 查找的類型的整個過程。

解決方法

您呼叫 Collection.InsertOne(),可用來插入單一文件。然而,devicesReadings 是多個文件的一部分。

因此,您要么必須迭代所有文件並將它們單獨傳遞給Collection.InsertOne(),要么使用Collection.InsertMany()#,使用要插入的多個文件的切片。

以上是Mongodb 時間序列 / Golang -的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除