2

To print a collection from mongodb the following is my code in python:

print(list(MongoClient(***).get_database("ChatDB").get_collection("room_members".find({'_id.username': username})))

I am learning Go and I am trying to translate the aforementioned code into golang.

My code is as follows:

    client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("*****"))
    if err != nil {
        panic(err)
    }
    likes_collection := client.Database("ChatDB").Collection("likes")
    cur, err := likes_collection.Find(context.Background(), bson.D{{}})
    if err != nil {
        panic(err)
    }
    defer cur.Close(context.Background())
    fmt.Println(cur)

However, I get some hex value

2 Answers 2

3

Mongo in go lang different api than mongo.

Find returns cursor not collection.

You should changed your code to :

var items []Items 
cur, err := likes_collection.Find(context.Background(), bson.D{{}})
    if err != nil {
        panic(err)
    }
cur.All(context.Background(),&items)
Sign up to request clarification or add additional context in comments.

Comments

0
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, options.Client().ApplyURI("***"))
if err != nil {
    panic(err)
}
var likes []bson.M
likes_collection := client.Database("ChatDB").Collection("likes")

defer client.Disconnect(ctx)

cursor, err := likes_collection.Find(context.Background(), bson.D{{}})
if err != nil {
    panic(err)
}
if err = cursor.All(ctx, &likes); err != nil {
    panic(err)
}
fmt.Println(likes)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.