在使用$lookup时,产生聚合游标并不会直接返回一个包含所有文档的数组,而是返回一个MongoDB聚合游标对象。因此,我们需要手动解包并将结果存储到切片中。
以下是将聚合查询结果存储到切片中的示例代码:
pipeline := []bson.M{
bson.M{
"$lookup": bson.M{
"from": "collection2",
"localField": "field1",
"foreignField": "field2",
"as": "results",
},
},
}
cursor, err := collection1.Aggregate(context.TODO(), pipeline)
if err != nil {
// handle error
}
var results []bson.M
if err := cursor.All(context.TODO(), &results); err != nil {
// handle error
}
fmt.Println(results)
在上面的示例代码中,我们首先定义了一个MongoDB聚合管道pipeline,其中包含一个$lookup操作符,该操作符从另一个集合(在这种情况下是“collection2”)中查找匹配字段的文档。然后我们调用collection1.Aggregate()方法来获取MongoDB聚合游标。
使用游标对象的.All()方法可以将游标结果解包到切片中,我们在这里存储到results变量中,并最后打印结果。