
如何使用动态条件实现 mongodb mgo v2 中的聚合查询
当聚合查询中包含可选条件时,需要动态构造查询条件。mgo v2 中的 bson.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
}在这种情况下,如果 bankid 和 difficulty 为空字符串,则不会添加相应的查询条件。如果需要完全省略条件,可以使用 bson.d 类型进行构造。
以上就是## MongoDB mgo v2 中如何使用动态条件实现聚合查询?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号