Reputation: 185
I am using Go and MongoDB for my Project.I used
db.collection.aggregate([{$match:{}},{$lookup:{}},{$addFields:{}}])
it is working fine in MongoDB, but when I use pipeline in Go, it gives below error
The 'cursor' option is required, except for aggregate with the explain argument
Go code is
matchStage:=bson.M{"$match":bson.M{}}
pipeline := collection.Pipe([]bson.M{matchStage})
err = pipeline.All(&resp)
Upvotes: 1
Views: 330
Reputation: 3349
This is not how you are supposed to implement Mongo-Aggregation query in Go.
It should be of the format
cursor, err := collection.Aggregate(
ctx,
mongo.Pipeline{<PIPELINE-STAGES>},
options.Aggregate().SetAllowDiskUse(true),
)
Hence your code should be:
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)
}
Note: I haven't tested the code in my local. So let me know in case of errors.
Upvotes: 1