首頁  >  文章  >  後端開發  >  Golang mongodb 聚合錯誤:管道階段規格物件必須僅包含一個字段

Golang mongodb 聚合錯誤:管道階段規格物件必須僅包含一個字段

WBOY
WBOY轉載
2024-02-02 14:13:21817瀏覽

Golang mongodb 聚合错误:管道阶段规范对象必须仅包含一个字段

問題內容

我想取得過去一個月內按名稱分組的計數。當我嘗試在 golang mongo 用戶端中執行以下查詢。我收到錯誤:

error: 管道階段規範物件必須只包含一個欄位。

cond := &bson.D{
        bson.E{Key: "$createTime", Value: bson.E{Key: "$gte", Value: time.Now().AddDate(0, -1, 0)}},
    }
    match := bson.D{{Key: "$match", Value: cond}}
    group := bson.D{{Key: "$group", Value: bson.D{
        {Key: "_id", Value: "$name"},
        {Key: "count", Value: bson.D{{Key: "$sum", Value: 1}}},
    }}}
    cursor, err := col.Aggregate(ctx, mongo.Pipeline{match, group})

我不知道該怎麼辦?


正確答案


透過進行以下調整,我能夠獲得所需的結果:

  • $createTime 更改為 createTime,我假設您的欄位名稱不以 $# 開頭
  • bson.E{Key: "$gte", Value: time.Now().AddDate(0, -1, 0)} 改為bson.D{{Key: "$gte", Value: time .Now().AddDate(0, -1, 0)}}
cond := &bson.D{
    bson.E{Key: "createTime", Value: bson.D{{Key: "$gte", Value: time.Now().AddDate(0, -1, 0)}}},
}
match := bson.D{{Key: "$match", Value: cond}}
group := bson.D{{Key: "$group", Value: bson.D{
    {Key: "_id", Value: "$name"},
    {Key: "count", Value: bson.D{{Key: "$sum", Value: 1}}},
}}}
cursor, err := col.Aggregate(context.TODO(), mongo.Pipeline{match, group})

if err != nil {
    log.Println("Error: ", err)
}

調試此類問題的一些技巧:

  • 總是檢查 err 變數中傳回的錯誤訊息
  • 您可以透過以下方式啟用原始資料庫指令日誌記錄:
uri := options.Client().ApplyURI(appSettings.MongoDbUri)

if appSettings.LogDatabaseCommands {
    cmdMonitor := &event.CommandMonitor{
        Started: func(_ context.Context, evt *event.CommandStartedEvent) {
            log.Print(evt.Command)
        },
    }
    uri.SetMonitor(cmdMonitor)
}

以上是Golang mongodb 聚合錯誤:管道階段規格物件必須僅包含一個字段的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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