首頁 > 後端開發 > Golang > 主體

減法聚合 Mongo 文件 Golang

WBOY
發布: 2024-02-08 21:05:36
轉載
1124 人瀏覽過

减法聚合 Mongo 文档 Golang

php小編子墨今天為大家介紹減法聚合 Mongo 文件 Golang。在Golang開發中,使用MongoDB作為資料庫是非常常見的選擇。而MongoDB提供了強大的聚合框架,可以對文件進行各種複雜的聚合操作。其中,減法聚合是一種特殊的聚合操作,可以用來計算文件中某個欄位的差值。本文將詳細介紹如何在Golang中使用減法聚合來處理Mongo文檔,幫助開發者更好地理解並應用這項功能。

問題內容

我在 mongo 中有這個文件

{
  "_id": {
    "$oid": "649d3d688a1f30bf82e77342"
  },
  "test_value": {
    "$numberlong": "10"
  }
}
登入後複製

我想用這個 golang 程式碼將「test_value」減一

jsonInput := []map[string]interface{}{
        {
            "$match": map[string]interface{}{
                "test_value": 10,
            },
        },
        {
            "$set": map[string]interface{}{
                "test_value": map[string]interface{}{
                    "$subtract": []interface{}{"test_value", 1}},
            },
        },
    })


    value, bsonByte, errMarshal := bson.MarshalValue(jsonInput)
    if errMarshal != nil {
        modules.DoLog("ERROR", "", "MongoService", "aggregateDocument", "cannot Marshal jsonInput to BSONByte", true, errMarshal)
        ctx.IndentedJSON(200, gin.H{
            "error": errMarshal.Error(),
        })
        return
    }
    fmt.Println(value)
    
    bsonD := bson.A{}

    errUnmarshal1 := bson.UnmarshalValue(value, bsonByte, &bsonD)
    if errUnmarshal1 != nil {
        modules.DoLog("ERROR", "", "MongoService", "aggregateDocument", "cannot Unmarshal BSONByte to BSOND", true, errUnmarshal1)
        ctx.IndentedJSON(200, gin.H{
            "error": errUnmarshal1.Error(),
        })
        return
    }
    
    _, err := Client.Database("rhanov_queries").Collection(collectionName).Aggregate(ContextMongo, bsonD)
    if err != nil {
        modules.DoLog("ERROR", "", "MongoService", "aggregateDocument", "cannot aggregate document to Mongo", true, err)
        ctx.IndentedJSON(200, gin.H{
            "error": err,
        })
    }
登入後複製

我收到此錯誤

「無法將文件聚合到 mongo。無法將基元類型編組到 bson 文件:writearray 只能在位於元素或值上但位於頂層時寫入數組」

我做錯了什麼?


正確答案


"$subtract": []interface{}{"test_value", 1}
登入後複製

請注意,這裡 "test_value" 是一個文字。該表達式的意思是從字串test_value中減去數字1,這是無效的,不是你想要的。您想要改為引用字段路徑。因此,您應該在其前面加上 $ 前綴(請參閱 聚合表達式)。這是更正後的程式碼:

"$subtract": []interface{}{"$test_value", 1}
登入後複製

ps 1

為了方便其他人調查問題,請在以後提供一個最小的可執行重現器,例如:

package main

import (
    "context"
    "fmt"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
    jsoninput := []map[string]interface{}{
        {
            "$match": map[string]interface{}{
                "test_value": 10,
            },
        },
        {
            "$set": map[string]interface{}{
                "test_value": map[string]interface{}{
                    "$subtract": []interface{}{"test_value", 1},
                    // `test_value` should be prefixed with $ like this:
                    // "$subtract": []interface{}{"$test_value", 1},
                },
            },
        },
    }

    typ, buf, err := bson.marshalvalue(jsoninput)
    if err != nil {
        panic(err)
    }
    fmt.println(typ)

    var bsond bson.a

    if err := bson.unmarshalvalue(typ, buf, &bsond); err != nil {
        panic(err)
    }

    client, err := mongo.connect(context.background(), options.client().applyuri("mongodb://localhost"))
    if err != nil {
        panic(err)
    }
    collection := client.database("demo").collection("values")
    cur, err := collection.aggregate(context.background(), bsond)
    if err != nil {
        panic(err)
    }
    defer cur.close(context.background())
    for cur.next(context.background()) {
        fmt.printf("%+v", cur.current)
    }
}
登入後複製

並初始化收集資料:

db.values.insert({ _id: objectid('649d3d688a1f30bf82e77342'), test_value: 10 })
登入後複製

(在 mongodb shell 中執行)

使用軟體包go.mongodb.org/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e3331303931733a2c37283b2c1e286f706f6」保護]</a>mongo:5.0.8,我得到的錯誤是:

panic: (typemismatch) failed to optimize pipeline :: caused by :: can't $subtract int from string
登入後複製

ps 2:

#如果您不知道,您可以直接建立 bsond 變量,如下所示:

bsonD := bson.A{
    bson.M{
        "$match": bson.M{
            "test_value": 10,
        },
    },
    bson.M{
        "$set": bson.M{
            "test_value": bson.M{
                "$subtract": bson.A{"$test_value", 1},
            },
        },
    },
}
登入後複製

ps 3

您顯示的程式碼存在語法錯誤(jsoninput 的簡短聲明末尾有一個額外的 ))。更正此錯誤後,我認為它不會導致您在問題中顯示的錯誤。我相信錯誤是針對另一個 jsoninput 值。

以上是減法聚合 Mongo 文件 Golang的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!