表格的多条件查询 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"
)
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 {
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")
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
}