我有这个函数,它使用官方的 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)
}
}
它尝试在数据库中查找与 if 语句相关的两个条件的数据。如果未定义 subItemKey,则它会搜索与传入结构体的精确匹配项,如果定义了该键,则它会使用 $eq
运算符在数据中搜索匹配项特定领域。
这适用于 subItemKey 为空的情况。像这样:
database.FindItemMongo(dataStruct, "", "users")
给予
api | 1:36:55 app | value of found parsed
api | map[_id:ObjectID("8494398fsfd") data:map[email:qwer password:wer token:...]]
但是,如果我使用命令:
database.FindItemMongo(dataStruct, "Email", "users")
我什么也没得到。
我在 else 语句中定义 searchData 的方式不正确,我不确定是什么。有人看出出了什么问题吗?
编辑
我应该提到的是
的结果 unmarshalledSearch := bson.M{"data": bson.M{strings.ToLower(subItemKey): bson.M{"$eq": subItemString}}}
fmt.Println("value of unmarshalledSearch")
fmt.Println(unmarshalledSearch)
是
api | value of unmarshalledSearch
api | map[data:map[email:map[$eq:qwer]]]
这与从空字段查询返回的数据的格式相同。这是问题的关键 - 如果 searchData 的格式似乎正确,为什么光标没有返回任何结果?
最佳答案
我是 Golang 新手,没有环境来测试它,但我认为您应该从 MongoDB Documentation 中的示例开始并改变
var searchData []uint8
searchData, _ = bson.Marshal(bson.M{"data": bson.M{strings.ToLower(subItemKey): bson.M{"$eq": subItemString}}})
至
var searchData bson.D
searchData = bson.D{{"data." + strings.ToLower(subItemKey), bson.D{{"$eq", subItemString}}}}
对于 subItemKey
为空的情况,您绝对应该使用 bison.D
而不是 bison.M
,因为整个子文档都匹配如果字段顺序错误,您所做的将会失败。
对于搜索完全匹配的特殊情况,可以使用简化格式
searchData = bson.D{{"data." + strings.ToLower(subItemKey), subItemString}}
它可能无法解决您的问题,但它至少遵循推荐的模式。
如果这不能解决您的搜索问题,请在您的帖子中添加您正在使用的 Mongo 驱动程序和数据库的版本、您希望检索的完整文档、dataStruct
类型的声明,以及您传入的 dataStruct
的初始值设定项。
关于mongodb - Golang MongoDB 不返回条件查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54452205/