Assume that you are planning to make a point-of-sale system (POS) that will have the following features in mongodb
Define the Data Model
type Product struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Name string `json:"name,omitempty" bson:"name,omitempty"`
Price float64 `json:"price,omitempty" bson:"price,omitempty"`
Category string `json:"category,omitempty" bson:"category,omitempty"`
}
type Sale struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Products []Product `json:"products,omitempty" bson:"products,omitempty"`
TotalAmount float64 `json:"totalAmount,omitempty" bson:"totalAmount,omitempty"`
Timestamp time.Time `json:"timestamp,omitempty" bson:"timestamp,omitempty"`
}
Connect to MongoDB
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(context.Background())
Insert a Product into the Database
collection := client.Database("pos_db").Collection("products")
product := Product{Name: "Laptop", Price: 999.99, Category: "Electronics"}
insertResult, err := collection.InsertOne(context.Background(), product)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted a single product: ", insertResult.InsertedID)
Retrieve Sales from the Database
collection := client.Database("pos_db").Collection("sales")
cursor, err := collection.Find(context.Background(), bson.D{})
if err != nil {
log.Fatal(err)
}
defer cursor.Close(context.Background())
for cursor.Next(context.Background()) {
var sale Sale
err := cursor.Decode(&sale)
if err != nil {
log.Fatal(err)
}
fmt.Println(sale)
}
Calculate Total Sales Amount
collection := client.Database("pos_db").Collection("sales")
pipeline := bson.A{
bson.D{{"$group", bson.D{{"_id", nil}, {"total", bson.D{{"$sum", "$totalAmount"}}}}}},
}
cursor, err := collection.Aggregate(context.Background(), pipeline)
if err != nil {
log.Fatal(err)
}
defer cursor.Close(context.Background())
for cursor.Next(context.Background()) {
var result bson.M
err := cursor.Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Println("Total sales amount:", result["total"])
}