【发布时间】:2021-08-02 19:56:36
【问题描述】:
我的 mongoDB 数据库中有一个非常简单的条目:
{"_id":{"$oid":"609b15511a048e03dda05861"},"password":"test_password","answer":"test_answer"}
当我在 Atlas UI 中使用过滤器参数时,我能够提取结果。
过滤器:
{"password": "test_password"}
但是,当我调用数据库时,我不断收到错误 mongo: no documents in result
filter := bson.M{"password": "test_password"}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err := collection.FindOne(ctx, filter).Decode(&result)
if err != nil {
log.Printf("%v", err)
}
我似乎正在正确连接到该集合。有什么想法吗?
【问题讨论】:
-
您发布的代码应该可以工作,问题出在其他地方(我们不知道)。测试您是否可以使用空过滤器获取其他(所有)文档。
-
result的定义是什么?另外,尝试使用ctx.TODO()进行查找。一般来说,最好使用bson.D来定义查询filter(bson.M 不能保证条目的顺序 - 与多个过滤条件相关)。 -
result定义为type Result struct { Password stringjson:"password"` 答案字符串json:"answer}. And I'll try thatctx.TODO()` -
我似乎无法用空过滤器得到任何东西。也许我根本没有连接?
标签: mongodb go mongo-go mongo-go-driver