go练习 day03

表格的多条件查询 mongodb数据库
摸瞎自学~
const (
	STRING = "string"
	ARRAY_TYPE = "[]interface {}"
	MAP_TYPE = "map[string]interface {}"
	BOOL = "bool"
	INT = "int"
	INT32 = "int32"
	INT64 = "int64"
	FLOAT = "float"
	FLOAT32 = "float32"
	FLOAT64 = "float64"
)

// 参数处理 根据请求体参数处理成查询所需要的bson结构
func GetDealParams(params map[string]interface{}) primitive.M {
	filter := bson.M{}
	for key, val := range params {
		// 获取字段的类型
		valType := GetType(val)
		// 字段类型转字符串
		sType := fmt.Sprintf("%v", valType)
		fmt.Println(sType, "sType")
		if sType == STRING  && val != "" {
			filter[key] = bson.M{"$regex": val}
		} 
		if sType == BOOL || sType == INT || sType == INT32 || sType == INT64 || sType == FLOAT || sType == FLOAT32 || sType == FLOAT64 {
			filter[key] = val
		} 
		// 对象数组类型处理
		if sType == ARRAY_TYPE {
			f := GetDealArrayParams(val)
			filter[key] = f
		}
		// 对象类型处理
		if sType == MAP_TYPE {
			f := GetDealParams(val.(map[string]interface{}))
			filter[key] = f
		}
	}

	return filter
}


func GetDealArrayParams (params interface{}) primitive.M{
	t := params.([]interface{})
	f := bson.M{}
	for _, iv := range t {
		ff := bson.M{}
		if fmt.Sprintf("%v", GetType(iv)) == STRING {
			// fmt.Println(iv, "iviviviv")
			ff["$eq"] = iv
		} else {
			// 遍历外层数组
			for kk, vv := range iv.(map[string]interface{}) {
				valCType := GetType(vv)
				cType := fmt.Sprintf("%v", valCType)
				if cType == STRING  && vv != "" {
					ff[kk] = bson.M{"$regex": vv}
				} 
				if cType == BOOL || cType == INT || cType == INT32 || cType == INT64 || cType == FLOAT || cType == FLOAT32 || cType == FLOAT64 {
					ff[kk] = vv
				} 
				if cType == ARRAY_TYPE {
					ff[kk] = GetDealArrayParams(vv)
				}
				if cType == MAP_TYPE {
					ff[kk] = GetDealParams(vv.(map[string]interface{}))
				}
			}
		}
		
		f["$elemMatch"] = ff
	}
	return f
}

func (m *RecordDao) GetRecordList(iRecordDTO map[string]interface{}) ([]model.Record, int64, error){
	var giRecordList []model.Record
	
	collection := m.MDB.Database("lowcode").Collection("lowcode")
	// 获取bson格式的请求数据
	filter := utils.GetDealParams(iRecordDTO)
	fmt.Println(filter, "filter")
	// 根据请求数据 获取查询内容
	cursor, err := collection.Find(context.Background(), filter)
	cursor.All(context.Background(), &giRecordList)
	// 根据请求数据 获取数量信息
	count, err := collection.CountDocuments(context.Background(), filter)  

	return giRecordList, count, err
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值