【问题标题】:mongodb go: `mongo: no documents in result`mongodb go:`mongo:结果中没有文档`
【发布时间】: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 string json:"password"` 答案字符串json:"answer }. And I'll try that ctx.TODO()`
  • 我似乎无法用空过滤器得到任何东西。也许我根本没有连接?

标签: mongodb go mongo-go mongo-go-driver


【解决方案1】:

毕竟我没有正确连接到数据库。

我像这样连接到我的收藏:

collection := client.Database("DB_NAME").Collection("COLLECTION_NAME")

而且由于它没有抛出错误,我错误地认为这是正确的。您可以通过以下方式查看您的收藏和数据库:

databases, _ := client.ListDatabaseNames(ctx, bson.M{})
log.Printf("%v", databases)
collections, _ := client.Database("DATABASES").ListCollectionNames(ctx, bson.M{})
log.Printf("%v", collections)

【讨论】:

    猜你喜欢
    • 2019-03-12
    • 1970-01-01
    • 2018-09-30
    • 2017-05-06
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    相关资源
    最近更新 更多