亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

需要光標選項

需要光標選項

Go
狐的傳說 2022-06-21 09:49:04
我在我的項目中使用 Go 和 MongoDB。我用過db.collection.aggregate([{$match:{}},{$lookup:{}},{$addFields:{}}])它在 MongoDB 中運行良好,但是當我在 Go 中使用管道時,出現以下錯誤The 'cursor' option is required, except for aggregate with the explain argument去代碼是matchStage:=bson.M{"$match":bson.M{}}pipeline := collection.Pipe([]bson.M{matchStage})    err = pipeline.All(&resp)
查看完整描述

1 回答

?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

這不是你應該在 Go 中實現 Mongo-Aggregation 查詢的方式。


它應該是格式


cursor, err := collection.Aggregate(

        ctx,

        mongo.Pipeline{<PIPELINE-STAGES>},

        options.Aggregate().SetAllowDiskUse(true),

        )

因此,您的代碼應該是:


ctx, _ = context.WithTimeout(context.Background(), 2*time.Second)


matchStage := bson.D{

        {"$match", bson.D{}},

    }

lookupStage := bson.D{

        {"from", ""},

        {"let": bson.D{{}}},

        {"pipeline": bson.A{}},

        {"as": ""},

    }

addFieldsStage := bson.D{

        {"$addFields", bson.D{}},

    }


cursor, err := collection.Aggregate(

    ctx,

    mongo.Pipeline{matchStage, lookupStage, addFieldsStage},

    options.Aggregate().SetAllowDiskUse(true),  // Mongo-Aggregate options if any

    )

if err != nil {

    panic(err)

}


for cursor.Next(ctx) {

    var cursorResult bson.M

    err := cursor.Decode(&cursorResult)  // I world recommend to decode it using a struct instead

    if err != nil {

        panic(err)

    }


    fmt.Printf("Decoded Cursor: %v", cursorResult)

}


err = cursor.Close(ctx)

if err != nil {

  panic(err)

}


注意:我沒有在本地測試過代碼。因此,如果出現錯誤,請告訴我。


查看完整回答
反對 回復 2022-06-21
  • 1 回答
  • 0 關注
  • 102 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號