Connessione a MongoDB in Go
In questo articolo vediamo come connetterci ad un database MongoDB in Go ed eseguire alcune operazioni.
Il db in questione è installato su un server della rete locale, quindi non è uno dei servizi in cloud; ma comunque cambia poco, praticamente solo l'url.
Prima di tutto installiamo queste due librerie:
go get go.mongodb.org/mongo-driver/v2/mongo
go get go.mongodb.org/mongo-driver/bson
Qui sotto vi posto tutto il codice:
package main
import (
"context"
"fmt"
"os"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://192.168.0.94:27017"))
if err != nil {
fmt.Println(err)
os.Exit(0)
}
err = client.Ping(context.Background(), nil)
if err != nil {
fmt.Println(err)
os.Exit(0)
}
fmt.Println("Connessione avvenuta")
collection := client.Database("test").Collection("persone")
persone := []interface{}{
bson.D{{"email", "a@a.it"}, {"age", 40}},
bson.D{{"email2", "a2@a.it"}, {"telefono", "65465165"}},
bson.D{{"email3", "a3@a.it"}, {"lavoro", "consulente"}},
}
results, err := collection.InsertMany(context.Background(), persone)
if err != nil {
fmt.Println(err)
os.Exit(0)
}
fmt.Println(results.InsertedIDs)
cursor, err := collection.Find(context.Background(), bson.D{})
if err != nil {
fmt.Println(err)
os.Exit(0)
}
var records []bson.M
if err = cursor.All(context.Background(), &records); err != nil {
fmt.Println(err)
os.Exit(0)
}
for _, result := range records {
fmt.Println(result)
}
}
Qui ci connettiamo, facciamo un inserimento massivo ed una query.
Vi lascio le altre operazioni come studio.
Enjoy!
go database mongodb
Commentami!