dongzz4545 2019-01-31 01:49
浏览 251

Golang MongoDB不返回条件查询

I have this function which uses the official mongo-go-driver (https://github.com/mongodb/mongo-go-driver)

func FindItemMongo(dataStruct interface{}, subItemKey string, collectionName string)(){
    fmt.Println("inside FindDataMongo in Controller")
    localDB := DB
    coll := localDB.Collection(collectionName)
    ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
    var searchData []uint8
    if subItemKey==""{
        fmt.Println("inside no key searchData")
        searchData, _ = bson.Marshal(bson.M{"data": dataStruct})
        fmt.Println("value of searchData")
        fmt.Println(searchData)
        fmt.Println("value of reflect type of searchData")
        fmt.Println(reflect.TypeOf(searchData))
    }else{
        reflectItem := reflect.ValueOf(dataStruct)
        subItem := reflectItem.FieldByName(subItemKey)
        subItemString := subItem.Interface().(string)
        searchData, _ =  bson.Marshal(bson.M{"data": bson.M{strings.ToLower(subItemKey): bson.M{"$eq": subItemString}}})
        fmt.Println("value of searchData")
        fmt.Println(searchData)
        fmt.Println("value of reflect type of searchData")
        fmt.Println(reflect.TypeOf(searchData))
    }
    cursor, err := coll.Find(ctx, searchData)
    if err != nil {
        log.Fatal(err)
    }
    defer cursor.Close(ctx)
    var returnBson []map[string]interface{}
    var result bson.M
    for cursor.Next(ctx) {
        err := cursor.Decode(&result)
        if err != nil { log.Fatal(err) }
        fmt.Println("value of found parsed")
        fmt.Println(result)
        returnBson = append(returnBson, result)
    }
}

Which is attempting to find data that is in the database for two conditions, related to the if statement. If the subItemKey is not defined, then it searches for an exact match to the passed in struct, if the key is defined, then it searches for a match in the data using the $eq operator for only a specific field.

This works for the condition where the subItemKey is empty. Like this:

database.FindItemMongo(dataStruct, "", "users")

Gives

api       | 1:36:55 app         | value of found parsed
api       | map[_id:ObjectID("8494398fsfd") data:map[email:qwer password:wer token:...]]

However, if I use the command:

database.FindItemMongo(dataStruct, "Email", "users")

I get nothing.

Something is not correct with how I define searchData in the else statement and I'm not sure what. Does anyone see what is going wrong?

EDIT

I should mention that the result of

    unmarshalledSearch := bson.M{"data": bson.M{strings.ToLower(subItemKey): bson.M{"$eq": subItemString}}}
    fmt.Println("value of unmarshalledSearch")
    fmt.Println(unmarshalledSearch)

is

api       | value of unmarshalledSearch
api       | map[data:map[email:map[$eq:qwer]]]

which is the same format as the data that is coming back from the empty field query. This is the crux of the problem - if the searchData appears to be correctly formatted, why is the cursor not returning with any results?

  • 写回答

3条回答 默认 最新

  • dongtu1357 2019-02-02 03:32
    关注

    I'm new to Golang and do not have an environment to test this, but I think you should start by following the examples in the MongoDB Documentation and change

    var searchData []uint8
        searchData, _ =  bson.Marshal(bson.M{"data": bson.M{strings.ToLower(subItemKey): bson.M{"$eq": subItemString}}})
    

    to

    var searchData bson.D
        searchData = bson.D{{"data." + strings.ToLower(subItemKey), bson.D{{"$eq", subItemString}}}}
    

    You definitely should use bison.D and not bison.M for the case where subItemKey is empty because the whole sub-document match you are doing will fail if the fields are in the wrong order.

    For the special case of searching for exact match, you can use the simplified format

        searchData = bson.D{{"data." + strings.ToLower(subItemKey), subItemString}}
    

    It might not solve your problem but it does at least follow the recommended pattern.

    If that does not fix your search, please add to your post the versions of the Mongo driver and database you are using, the full document you expect to retrieve, the declaration of the dataStruct type, and the initializer for the dataStruct that you are passing in.

    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 matlab求解平差
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办