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)
}
注意:我沒有在本地測試過代碼。因此,如果出現錯誤,請告訴我。
- 1 回答
- 0 關注
- 102 瀏覽
添加回答
舉報