需要光标选项

我在我的项目中使用 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)


狐的传说
浏览 115回答 1
1回答

沧海一幻觉

这不是你应该在 Go 中实现 Mongo-Aggregation 查询的方式。它应该是格式cursor, err := collection.Aggregate(&nbsp; &nbsp; &nbsp; &nbsp; ctx,&nbsp; &nbsp; &nbsp; &nbsp; mongo.Pipeline{<PIPELINE-STAGES>},&nbsp; &nbsp; &nbsp; &nbsp; options.Aggregate().SetAllowDiskUse(true),&nbsp; &nbsp; &nbsp; &nbsp; )因此,您的代码应该是:ctx, _ = context.WithTimeout(context.Background(), 2*time.Second)matchStage := bson.D{&nbsp; &nbsp; &nbsp; &nbsp; {"$match", bson.D{}},&nbsp; &nbsp; }lookupStage := bson.D{&nbsp; &nbsp; &nbsp; &nbsp; {"from", ""},&nbsp; &nbsp; &nbsp; &nbsp; {"let": bson.D{{}}},&nbsp; &nbsp; &nbsp; &nbsp; {"pipeline": bson.A{}},&nbsp; &nbsp; &nbsp; &nbsp; {"as": ""},&nbsp; &nbsp; }addFieldsStage := bson.D{&nbsp; &nbsp; &nbsp; &nbsp; {"$addFields", bson.D{}},&nbsp; &nbsp; }cursor, err := collection.Aggregate(&nbsp; &nbsp; ctx,&nbsp; &nbsp; mongo.Pipeline{matchStage, lookupStage, addFieldsStage},&nbsp; &nbsp; options.Aggregate().SetAllowDiskUse(true),&nbsp; // Mongo-Aggregate options if any&nbsp; &nbsp; )if err != nil {&nbsp; &nbsp; panic(err)}for cursor.Next(ctx) {&nbsp; &nbsp; var cursorResult bson.M&nbsp; &nbsp; err := cursor.Decode(&cursorResult)&nbsp; // I world recommend to decode it using a struct instead&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("Decoded Cursor: %v", cursorResult)}err = cursor.Close(ctx)if err != nil {&nbsp; panic(err)}注意:我没有在本地测试过代码。因此,如果出现错误,请告诉我。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go