为了账号安全,请及时绑定邮箱和手机立即绑定

需要光标选项

需要光标选项

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 关注
  • 114 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号