英文:
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})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论