卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35428本站已运行396

过滤查询 mongodb Golang

过滤查询 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{...}:

将它们一起提交给 .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
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏