如何在Golang的MongoDB中同时使用count和or表达式?

huangapple go评论71阅读模式
英文:

how to use count and or expression at same time golang mongodb?

问题

嗨,我写了这些代码,但是当我尝试运行时,它只返回当总数大于我给定的数字时,并且它没有使用checked字段。我的意思是,我有6个文档,其中5个是true,但它给我返回了6个结果!

checked := bson.D{{"$or", []interface{}{bson.D{{"checked", false}}, bson.D{{"checked", nil}}}}}
totalReport := bson.D{{"total", bson.D{{"$gte", config.ReportNumberToChangeNickname}}}}
totalReportAndChecked := bson.D{{"$and", []interface{}{checked, totalReport}}}
matchStage := bson.D{{"$match", totalReportAndChecked}}
groupStage := bson.D{{"$group", bson.D{{"_id", "$user_id"}, {"total", bson.D{{"$sum", 1}}}}}}
cursor, err := UserReportDb.Aggregate(ctx, mongo.Pipeline{groupStage, matchStage})
if err != nil {
    fmt.Println(err)
    return &mongo.Cursor{}, err
}
英文:

hi i write this line of codes but when i try it just return when total is greater then number i gave and it just doesn't use checked . i mean i have 6 documants and 5 of them are true but it give me 6 reuslt !

checked := bson.D{{"$or", []interface{}{bson.D{{"checked", false}}, bson.D{{"checked", nil}}}}}
totalReport := bson.D{{"total", bson.D{{"$gte", config.ReportNumberToChangeNickname}}}}
totalReportAndChecked := bson.D{{"$and", []interface{}{checked, totalReport}}}
matchStage := bson.D{{"$match", totalReportAndChecked}}
groupStage := bson.D{{"$group", bson.D{{"_id", "$user_id"}, {"total", bson.D{{"$sum", 1}}}}}}
cursor, err := UserReportDb.Aggregate(ctx, mongo.Pipeline{groupStage, matchStage})
if err != nil {
	fmt.Println(err)
	return &mongo.Cursor{}, err
}

答案1

得分: 0

我找到了答案,谢谢。

cond := bson.D{{"$cond", []interface{}{"$checked", 0, 1}}}

matchStage := bson.D{{"$match", bson.D{{"$expr", bson.D{{"$gte", []interface{}{"$total", config.ReportNumberToChangeNickname}}}}}}}

groupStage := bson.D{{"$group", bson.D{{"_id", "$user_id"}, {"total", bson.D{{"$sum", cond}}}, {"value", bson.D{{"$last", "$value"}}}}}}

cursor, err := UserReportDb.Aggregate(ctx, mongo.Pipeline{groupStage, matchStage})
英文:

i found the answer thanks

cond := bson.D{{"$cond", []interface{}{"$checked", 0, 1}}}

matchStage := bson.D{{"$match", bson.D{{"$expr", bson.D{{"$gte", []interface{}{"$total", config.ReportNumberToChangeNickname}}}}}}}

groupStage := bson.D{{"$group", bson.D{{"_id", "$user_id"}, {"total", bson.D{{"$sum", cond}}}, {"value", bson.D{{"$last", "$value"}}}}}}

cursor, err := UserReportDb.Aggregate(ctx, mongo.Pipeline{groupStage, matchStage})

huangapple
  • 本文由 发表于 2022年1月9日 14:12:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/70638882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定