过滤查询 mongodb Golang

2024年 2月 12日 60.8k 0

过滤查询 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()

此示例文档中的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})

登录后复制

以上就是过滤查询 mongodb Golang的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论