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

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

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

问题

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

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

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 !

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

答案1

得分: 0

我找到了答案,谢谢。

  1. cond := bson.D{{"$cond", []interface{}{"$checked", 0, 1}}}
  2. matchStage := bson.D{{"$match", bson.D{{"$expr", bson.D{{"$gte", []interface{}{"$total", config.ReportNumberToChangeNickname}}}}}}}
  3. groupStage := bson.D{{"$group", bson.D{{"_id", "$user_id"}, {"total", bson.D{{"$sum", cond}}}, {"value", bson.D{{"$last", "$value"}}}}}}
  4. cursor, err := UserReportDb.Aggregate(ctx, mongo.Pipeline{groupStage, matchStage})
英文:

i found the answer thanks

  1. cond := bson.D{{"$cond", []interface{}{"$checked", 0, 1}}}
  2. matchStage := bson.D{{"$match", bson.D{{"$expr", bson.D{{"$gte", []interface{}{"$total", config.ReportNumberToChangeNickname}}}}}}}
  3. groupStage := bson.D{{"$group", bson.D{{"_id", "$user_id"}, {"total", bson.D{{"$sum", cond}}}, {"value", bson.D{{"$last", "$value"}}}}}}
  4. 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:

确定