gpt4 book ai didi

mongodb - 需要光标选项

转载 作者:行者123 更新时间:2023-12-01 22:12:01 24 4
gpt4 key购买 nike

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

最佳答案

这不是您应该在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)
}

注意:我尚未在本地测试代码。因此,如果发生错误,请通知我。

关于mongodb - 需要光标选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63050979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com