0
votes

I have a pretty simple entry in my mongoDB database:

{"_id":{"$oid":"609b15511a048e03dda05861"},"password":"test_password","answer":"test_answer"}

And when I use filter parameters in the Atlas UI, I am able to pull up results.

Filter:

{"password": "test_password"}

However, when I call to the DB, I keep getting the error 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)
}

I appear to be connecting properly to the collection. Any thoughts?

1
The code you posted should work, the problem is somewhere else (unknown to us). Test if you can get other (all) documents with an empty filter.icza
What is the definition of result? Also, try the find with ctx.TODO(). In general, it is a better idea to use bson.D for defining the query filter (bson.M cannot guarantee the order of entries - relevant with multiple filter conditions).prasad_
result is defined as type Result struct { Password string json:"password"` Answer string json:"answer }. And I'll try that ctx.TODO()`Patrick Collins
I can't seem to get anything with an empty filter. Perhaps I'm not connected after all?Patrick Collins

1 Answers

0
votes

I wasn't connecting properly to the db after all.

I was connecting to my collection like so:

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

And since it didn't throw an error, I incorrectly assumed this was right. You can look at your collections and databases with the following:

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