Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

where := bson.M{"$match": bson.M{"user_id": userId, "bank_id": bankId, "knowledge_points": bson.M{"$in": Knowledge}, "difficulty": difficulty}}

num := bson.M{"$sample": bson.M{"size": questionNum}}

err := repo.collection().Pipe([]bson.M{where, num}).All(&b)
if err != nil {
    return nil, err
}

请教 以上代码 where 条件中 "knowledge_points": bson.M{"$in": Knowledge}, "difficulty": difficulty是可选项,如果有值才会进行匹配,请问该怎么写?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

经查 bson.M 是

type M map[string]interface{}

类型
所以这样就可以了

var query map[string]interface{}
    query = make(map[string]interface{})
    query["user_id"] = userId
    if bankId > 0 {
        query["bank_id"] = bankId
    }
    if difficulty != "" {
        query["difficulty"] = difficulty
    }
    
    where := bson.M{"$match": query}

    num := bson.M{"$sample": bson.M{"size": questionNum}}

    err := repo.collection().Pipe([]bson.M{where, num}).All(&b)
    if err != nil {
        return nil, err
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...