登录
首页 >  Golang >  Go问答

使用 Golang 对 MongoDB 进行查询过滤

来源:stackoverflow

时间:2024-02-08 10:36:26 429浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《使用 Golang 对 MongoDB 进行查询过滤》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

我正在尝试获取与特定查询匹配的数据列表,但收到此错误

"(atlaserror) merchant is not allowed or the syntax is incorrect, see
the atlas documentation for more information"
func ...

var result []*model.Package

    ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
    defer cancel()

    tokenData, err := middleware.CtxValue(ctx)

    if err != nil {
        return nil, err
    }

    orQuery := []bson.M{}
    merchant := "abc"
    completedQuery := bson.M{"status": "completed"}
    cancelledQuery := bson.M{"status": "cancelled"}
    orQuery = append(
        orQuery,
        cancelledQuery,
        completedQuery)
    limit64 := int64(limit)
    page64 := int64(page)
    match := bson.M{"$match": bson.M{"$nor": orQuery}}
    var filterQuery primitive.M

    if tokenData.Role == "admin" && merchant != nil {
        filterQuery = bson.M{"merchant": bson.M{"id": merchant}}
    } else {
        filterQuery = bson.M{"user": bson.M{"id": tokenData.Id}}
    }
    paginatedData, err1 := paginate.New(r.Collection).Context(ctx).Limit(limit64).Page(page64).Aggregate(match, filterQuery)
    if err1 != nil {
        return nil, err1
    }


...

正确答案


filterquery,似乎包含 { "merchant" : { "id" : "abc" } },被单独传递给 .aggregate()。但是聚合框架期望接收代表一系列管道阶段的东西。 文档中概述了每个阶段,预计以 $ 字符开头,例如 $match 阶段。

当前数据库正在尝试将 merchant 作为管道的 options 进行处理(请参阅 这里此处)。但这样的选项不存在,因此出现错误消息。

要解决此问题,您应该将 filterquery 逻辑合并到您正在构建和传递的现有 match 变量/阶段中。或者,您可以将 filterquery 包装在不同的 $match 中,然后将它们(作为单个参数)传递给 .aggregate()

此示例文档中的a>显示他们构建了多个阶段并且然后通过 mongo.pipeline{...}:

将它们一起提交给 .aggregate()
// create the stages
matchStage := bson.D{{"$match", bson.D{{"toppings", "milk foam"}}}}
unsetStage := bson.D{{"$unset", bson.A{"_id", "category"}}}
sortStage := bson.D{{"$sort", bson.D{
    {"price", 1},
    {"toppings", 1}},
}}
limitStage := bson.D{{"$limit", 2}}

// pass the stage into a pipeline
// pass the pipeline as the second paramter in the Aggregate() method
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, unsetStage, sortStage, limitStage})

终于介绍完啦!小伙伴们,这篇关于《使用 Golang 对 MongoDB 进行查询过滤》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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