Reputation: 184
I'm new to mongodb and go and was trying to follow an example, but can't check for data in mongo shell since they return different results
my go code
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
//Trainer You will be using this Trainer type later in the program
type Trainer struct {
Name string
Age int
City string
}
func main() {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
collection := client.Database("db_test").Collection("trainers")
ash := Trainer{"Ash", 10, "Pallet Town"}
misty := Trainer{"Misty", 10, "Cerulean City"}
brock := Trainer{"Brock", 15, "Pewter City"}
trainers := []interface{}{ash, misty, brock}
insertResult, err := collection.InsertMany(context.TODO(), trainers)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted a single document: ", insertResult.InsertedIDs)
result, err := collection.Find(context.TODO(), bson.D{}, options.Find())
if err != nil {
log.Fatal(err)
}
fmt.Println("Find Failed.")
for result.Next(context.TODO()) {
var singleRow Trainer
err := result.Decode(&singleRow)
if err != nil {
log.Fatal(err)
}
fmt.Println(singleRow.Name, "+", singleRow.Age)
}
fmt.Println("Find finished")
err = client.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")
}
this returns
Connected to MongoDB!
Inserted a single document: [ObjectID("5da929e60a2ef8952d92ce8c") ObjectID("5da929e60a2ef8952d92ce8d") ObjectID("5da929e60a2ef8952d92ce8e")]
Find Failed.
Ash + 10
Misty + 10
Brock + 15
Find finished
Connection to MongoDB closed.
the mongo shell
Is it because the mongo shell and my go code connect to different clusters or something?
Also I've tried using compass and it shows a different result than the mongo shell too. How do i know the shell is working properly?
My path environment was set to "C:\Program Files\MongoDB\Server\4.2\bin" so i dont think there's a problem with that
Upvotes: 0
Views: 563
Reputation: 1419
Try running your Go code, after replacing the following line
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
with this
clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb")
Upvotes: 1