首页 > 后端开发 > Golang > 正文

过滤查询 mongodb Golang

WBOY
发布: 2024-02-12 08:33:18
转载
736 人浏览过

过滤查询 mongodb Golang

php小编西瓜今天要为大家介绍的是关于过滤查询mongodb的Golang实现。在使用mongodb数据库进行数据查询时,我们经常需要对查询结果进行过滤,以满足特定的条件。Golang作为一种强大的编程语言,提供了丰富的mongodb驱动库,可以方便地实现过滤查询功能。接下来,我们将详细介绍如何在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()

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

将它们一起提交给 .aggregate() 将它们一起提交给 .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})
登录后复制

以上是过滤查询 mongodb Golang的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!