猿问

golang mongodb如何同时使用count和or表达式?

我写了这行代码,但是当我尝试它时,它只是在总大于我给出的数字时返回,它只是不使用检查。我的意思是我有 6 个文档,其中 5 个是真实的,但它给了我 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

}


莫回无
浏览 82回答 1
1回答

繁星点点滴滴

我找到了答案谢谢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})
随时随地看视频慕课网APP

相关分类

Go
我要回答