使用Golang MongoDB驱动时FindOne()始终返回空值求助
问题:Golang MongoDB驱动查询文档返回空结果
尝试用Golang的MongoDB驱动查询文档,但结果始终为空,返回"No matched documents!"日志。
我的代码:
var bsonString bson.M var jsonString string fmt.Printf("[%s] > request for url\n", req.RemoteAddr) w.Header().Set("Access-Control-Allow-Origin", "*") dataSource := client.Database(dbName) collection := dataSource.Collection(collectionName) err := collection.FindOne(context.Background(), bson.D{{"question.title", "Question"}}).Decode(&bsonString) if err != nil { if err == mongo.ErrNoDocuments { // This error means your query did not match any documents. log.Println("No matched documents!") return } panic(err) } finalBytes, _ := bson.Marshal(bsonString) bson.Unmarshal(finalBytes, &jsonString) fmt.Println(jsonString)
我的数据:
{"_id":{"$oid":"631c5c78e606582e2ad78e2d"},"question":{"title":"Question","create_by":"AZ","time":{"$numberLong":"1661394765044"},"detail":"<h4>info</h4>"},"answers":[{"create_by":"baa","time":{"$numberLong":"1661394765044"},"detail":"<h4>abc</h4>"}]}
解决办法
确认数据库与集合名称正确性:检查
dbName和collectionName变量的值,确保和MongoDB中实际的库名、集合名完全一致(MongoDB对库名、集合名大小写敏感)。验证客户端连接状态:在获取集合前,添加连接校验代码,确保客户端已成功连接MongoDB:
err := client.Ping(context.Background(), nil) if err != nil { panic(err) }排查查询条件匹配问题:
- 尝试将查询条件改用
bson.M格式,兼容性更好:err := collection.FindOne(context.Background(), bson.M{"question.title": "Question"}).Decode(&bsonString) - 直接在MongoDB Shell或Compass中执行
db.your_collection.find({"question.title": "Question"}),确认是否存在匹配的文档,排除数据本身的问题(比如字段值有隐藏空格、大小写不一致)。
- 尝试将查询条件改用
修复JSON转换代码:当前的BSON转JSON逻辑错误,
bson.Unmarshal无法直接解码到字符串类型,应替换为json.Marshal:finalBytes, err := json.Marshal(bsonString) if err != nil { panic(err) } jsonString := string(finalBytes) fmt.Println(jsonString)
内容的提问来源于stack exchange,提问作者Arthur Zhou
相关产品推荐
相关产品推荐

