Last active
May 18, 2019 09:03
-
-
Save narensgh/d11a1086c381212b6d31ab3abe6dcfda to your computer and use it in GitHub Desktop.
Connect to mongo using mongo-go-driver and map nested results using struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
//Sample user collection | |
db.users.findOne() | |
{ | |
"_id" : 1, | |
"attrs" : { | |
"name" : "Name #1", | |
"age" : 25, | |
"email" : "useremail1@gmail.com" | |
}, | |
"pid" : [ | |
1, | |
2, | |
6, | |
7, | |
8, | |
] | |
} | |
*/ | |
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"time" | |
"go.mongodb.org/mongo-driver/bson" | |
"go.mongodb.org/mongo-driver/mongo" | |
"go.mongodb.org/mongo-driver/mongo/options" | |
) | |
func main() { | |
connectMongo() | |
} | |
//UserAttrs User Attrs Mapping | |
type UserAttrs struct { | |
Name string `json:"name" bson:"name"` | |
Age int `json:"age" bson:"age"` | |
Email string `json:"email" bson:"email"` | |
} | |
//Users User Mapping | |
type Users struct { | |
ID int `json:"id" bson:"_id"` | |
Attrs UserAttrs | |
Pid []int32 `json:"pid", bson: "pid"` | |
} | |
func connectMongo() { | |
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) | |
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://127.0.0.1:27017")) | |
if err != nil { | |
fmt.Println(err) | |
} | |
collection := client.Database("go_mongo").Collection("users") | |
cur, err := collection.Find(ctx, bson.D{}) | |
if err != nil { | |
log.Fatal("Error while collection find", err) | |
} | |
defer cur.Close(ctx) | |
for cur.Next(ctx) { | |
users := Users{} | |
err := cur.Decode(&s) | |
if err != nil { | |
log.Fatal("Error while struct mapping :: ", err) | |
} | |
for i, v := range users.Pid { | |
fmt.Printf("Key is :: %d and Value is :: %d\n", i, v) | |
} | |
fmt.Println("attrs : ", users.Attrs, "name : ", users.Attrs.Name) | |
} | |
if err := cur.Err(); err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment