Ähnlich wie bei der Gruppierung in SQL unterstützt auch MongoDB dies. In diesem Kapitel wird erläutert, wie die statistische Analyse von MongoDB-Daten mithilfe von Golang implementiert wird.
Voraussetzung Tutorial
Bitte lesen Sie das untenstehende Voraussetzungstutorial:
Testdaten
Die Daten in der "orders" -Sammlung lauten wie folgt:
{ _id: 1, cust_id: "abc1", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: "A", amount: 50 }
{ _id: 2, cust_id: "xyz1", ord_date: ISODate("2013-10-01T17:04:11.102Z"), status: "A", amount: 100 }
{ _id: 3, cust_id: "xyz1", ord_date: ISODate("2013-10-12T17:04:11.102Z"), status: "D", amount: 25 }
{ _id: 4, cust_id: "xyz1", ord_date: ISODate("2013-10-11T17:04:11.102Z"), status: "D", amount: 125 }
{ _id: 5, cust_id: "abc1", ord_date: ISODate("2013-11-12T17:04:11.102Z"), status: "A", amount: 25 }
Gruppierung und Aggregierung
Führen Sie statistische Abfragen mit der Collection.Aggregate-Funktion durch.
Im Folgenden finden Sie ein Beispiel für statistische Analysen in MongoDB:
[
{ $match: { status: "A" } }, // Die erste Phase, Übereinstimmung der Dokumentdaten basierend auf Abfragekriterien
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } }, // Die zweite Phase, Gruppierung und Aggregierung
{ $sort: { total: -1 } } // Die dritte Phase, Sortierung der Ergebnisse
]
Äquivalentes SQL:
select sum(amount) as total from orders
where status="A"
group by cust_id
order by total desc
So erreichen Sie dasselbe in Golang:
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() {
var coll *mongo.Collection
// Der Code zum Herstellen einer Verbindung zu MongoDB und zum Abrufen von Sammlungsobjekten wird hier ausgelassen und kann im Schnellstart-Tutorial nachgeschlagen werden.
// Ausdruck für statistische Analyse, Verwendung der Golang-Datenstruktur zur Darstellung der nativen MongoDB-Syntax.
// Wenn Sie mit dem Golang-MongoDB-Datenmodell nicht vertraut sind, lesen Sie bitte die vorherigen Abschnitte.
pipeline := mongo.Pipeline{
{{"$match", bson.D{{"status", "A"}}}},
{{"$group", bson.D{{"_id", "$cust_id"}, {"total", bson.D{{"$sum", "$amount"}}}}}},
{{"$sort", bson.D{{"total", -1}}}
}
// Setzen Sie ein Timeout
opts := options.Aggregate().SetMaxTime(2 * time.Second)
// Führen Sie statistische Analyse durch
cursor, err := coll.Aggregate(
context.TODO(), // Kontextparameter
pipeline, // Statistischer Analyseausdruck
opts // Optionale Parameter
)
if err != nil {
log.Fatal(err)
}
// Definieren des Ergebnissatzes, Verwendung des Typs bson.M (ein Typ Map-Struktur) zum Speichern der Abfrageergebnisse
var results []bson.M
// Holen Sie alle Ergebnisse und speichern Sie sie in der results-Variablen
if err = cursor.All(context.TODO(), &results); err != nil {
log.Fatal(err)
}
// Iterieren Sie durch die Abfrageergebnisse
for _, result := range results {
fmt.Printf("id = %v , total = %v \n", result["_id"], result["total"])
}
}
Hinweis: Für weitere MongoDB-Aggregationsyntax verweisen Sie bitte auf MongoDB-Aggregationspipeline