Golang中MongoDB驱动预期接收BSON文档却遇到primitive.D类型的问题

Golang中MongoDB驱动预期接收BSON文档却遇到primitive.D类型的问题 大家好!我正在尝试使用Go驱动程序在MongoDB 5的$lookup阶段中嵌套一个管道,但遇到了这个错误:

"(AtlasError) Expected 'pipeline' to be BSON docs (or equivalent), but got primitive.D instead. Doc = [{from post} {localField translated_version} {foreignField _id} {pipeline [{$project [{slug 1}]}]} {as translated_version}]"

我的代码:

    lookup_translated_post := bson.D{
        {
            Key: "$lookup", Value: bson.D{
                {
                    Key: "from", Value: model_name,
                },
                {
                    Key: "localField", Value: "translated_version",
                },
                {
                    Key: "foreignField", Value: "_id",
                },
                {
                    Key: "pipeline", Value: bson.D{
                        {
                            Key: "$project", Value: bson.D{
                                {
                                    Key: "slug", Value: 1,
                                },
                            },
                        },
                    },
                },
                {
                    Key: "as", Value: "translated_version",
                },
            },
        },
    }

不明白我哪里做错了 :frowning: 已经尝试向Mongo社区寻求帮助,但没有得到答复。


更多关于Golang中MongoDB驱动预期接收BSON文档却遇到primitive.D类型的问题的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang中MongoDB驱动预期接收BSON文档却遇到primitive.D类型的问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


错误信息表明MongoDB期望pipeline字段接收的是BSON文档数组,但你提供的却是primitive.D类型。在MongoDB的$lookup阶段中,pipeline参数应该是一个BSON数组,而不是单个文档。

问题出在你的代码中pipeline字段的值是bson.D(单个文档),而实际上应该是一个包含管道阶段的数组bson.A

以下是修正后的代码:

lookup_translated_post := bson.D{
    {
        Key: "$lookup", Value: bson.D{
            {
                Key: "from", Value: model_name,
            },
            {
                Key: "localField", Value: "translated_version",
            },
            {
                Key: "foreignField", Value: "_id",
            },
            {
                Key: "pipeline", Value: bson.A{
                    bson.D{
                        {
                            Key: "$project", Value: bson.D{
                                {
                                    Key: "slug", Value: 1,
                                },
                            },
                        },
                    },
                },
            },
            {
                Key: "as", Value: "translated_version",
            },
        },
    },
}

关键修改是将pipeline字段的值从bson.D改为bson.A(BSON数组),并将$project阶段包装在这个数组中。这样MongoDB就能正确识别管道阶段的数组结构了。

回到顶部