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"
)
type Person struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
Name string `bson:"name,omitempty"`
Age int `bson:"age,omitempty"`
Email string `bson:"email,omitempty"`
CreatedAt time.Time `bson:"createdAt,omitempty"`
}
func main() {
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
collection := client.Database("your_database").Collection("persons")
// Create a new person
person := Person{
Name: "John Doe",
Age: 30,
Email: "[email protected]",
CreatedAt: time.Now(),
}
// Insert the person document into the collection
insertResult, err := collection.InsertOne(context.TODO(), person)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted document with ID:", insertResult.InsertedID)
// Query the person document
var result Person
filter := bson.D{{"name", "John Doe"}}
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found document: %+v\n", result)
}