Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

mongo mgo v2中 聚合查询 中怎么使用动态条件?

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是可选项,如果有值才会进行匹配,请问该怎么写?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

经查 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
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...