登录
首页 >  Golang >  Go问答

Golang 和 MongoDB 在使用 `$facet` 运算符时发生错误警报

来源:stackoverflow

时间:2024-02-17 12:18:20 176浏览 收藏

大家好,今天本人给大家带来文章《Golang 和 MongoDB 在使用 `$facet` 运算符时发生错误警报》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我像这样设置了我的 facet

    metadataStage := bson.D{
        {"$facet", bson.D{
            {"metadata", bson.A{bson.D{
                {"$group", bson.D{
                    {"_id", nil},
                    {"total", bson.D{{"$sum", 1}}}}}}, // get number of documents that matches the all above conditions
            }},
            {"data", bson.A{bson.D{
                //{"$sort", sortStage}, // sort by field and direction
                {"$skip", skip}, // skip number of documents
                {"$limit", limit}}}}, // limit them
        }},
    }

但是当我运行我的代码时,mongo driver 总是警告错误 a pipeline stage specification object must contains just one field.。我不认为这是语法错误。请帮助我,非常感谢


正确答案


数据方面的每个管道都应该是数组的元素

    metadatastage := bson.d{
        {"$facet", bson.d{
            {"metadata", bson.a{
                bson.d{{"$group", bson.d{
                    {"_id", nil},
                    {"total", bson.d{{"$sum", 1}}}}}}, // get number of documents that matches the all above conditions
            }},
            {"data", bson.a{
                //bson.d{{"$sort", sortstage}}, // sort by field and direction
                bson.d{{"$skip", skip}}, // skip number of documents
                bson.d{{"$limit", limit}}}}}, // limit them
        }}

或者,您可以明确表示您正在声明构面管道的各个阶段。

    metadataStage := bson.D{
        {"$facet", bson.D{
            {"metadata", mongo.Pipeline{
                bson.D{{"$group", bson.D{
                    {"_id", nil},
                    {"total", bson.D{{"$sum", 1}}}}}}, // get number of documents that matches the all above conditions
            }},
            {"data", mongo.Pipeline{
                //bson.D{{"$sort", sortStage}}, // sort by field and direction
                bson.D{{"$skip", skip}},      // skip number of documents
                bson.D{{"$limit", limit}}}}}, // limit them
        }}

到这里,我们也就讲完了《Golang 和 MongoDB 在使用 `$facet` 运算符时发生错误警报》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>