Heim  >  Artikel  >  Backend-Entwicklung  >  Wie rufe ich mit Go Elemente basierend auf mehreren Attributwerten in MongoDB ab?

Wie rufe ich mit Go Elemente basierend auf mehreren Attributwerten in MongoDB ab?

DDD
DDDOriginal
2024-10-26 01:31:28386Durchsuche

How to Retrieve Items Based on Multiple Attribute Values in MongoDB Using Go?

Elementliste durch Überprüfen mehrerer Attributwerte in MongoDB in Go abrufen

In MongoDB kann das Abrufen von Elementen basierend auf mehreren Attributwerten mit erreicht werden die Aggregationspipeline. Hier ist eine Go-Implementierung mit dem Paket mgo.v2:

<code class="go">import (
    "context"
    "fmt"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

func RetrieveItemListByMultipleAttributeValues(databaseName, collectionName string, venueIDs []string) (map[string]int, error) {
    ctx := context.Background()

    // Create a new MongoDB connection.
    session, err := mgo.Dial("mongodb://host:port")
    if err != nil {
        return nil, fmt.Errorf("Error dialing MongoDB: %w", err)
    }
    defer session.Close()

    // Select the database and collection.
    collection := session.DB(databaseName).C(collectionName)

    // Define the aggregation pipeline.
    pipeline := []bson.M{
        {"$match": bson.M{"venueList.id": bson.M{"$in": venueIDs}}},
        {"$unwind": "$venueList"},
        {"$match": bson.M{"venueList.id": bson.M{"$in": venueIDs}}},
        {"$unwind": "$venueList.sum"},
        {"$group": bson.M{
            "_id": "$venueList.sum.name",
            "count": bson.M{"$sum": "$venueList.sum.value"},
        }},
        {"$group": bson.M{
            "_id": nil,
            "counts": bson.M{
                "$push": bson.M{
                    "name": "$_id",
                    "count": "$count",
                },
            },
        }},
    }

    // Run the aggregation pipeline.
    resultIterator, err := collection.Pipe(pipeline).Iter()
    if err != nil {
        return nil, fmt.Errorf("Error running aggregation pipeline: %w", err)
    }

    // Create a map to store the aggregated results.
    result := make(map[string]int)

    // Decode each result and add it to the map.
    for resultIterator.Next(&result) {
        for _, count := range result["counts"].([]interface{}) {
            result[count.(map[string]interface{})["name"].(string)] = count.(map[string]interface{})["count"].(int)
        }
    }

    // Close the result iterator.
    resultIterator.Close()

    // Return the result map.
    return result, nil
}</code>

Das obige ist der detaillierte Inhalt vonWie rufe ich mit Go Elemente basierend auf mehreren Attributwerten in MongoDB ab?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn