ホームページ  >  記事  >  バックエンド開発  >  Go を使用して MongoDB の複数の属性値に基づいて項目を取得する方法

Go を使用して MongoDB の複数の属性値に基づいて項目を取得する方法

DDD
DDDオリジナル
2024-10-26 01:31:28386ブラウズ

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

Go で MongoDB の複数の属性値を確認して項目リストを取得する

MongoDB では、複数の属性値に基づいて項目を取得するには、次のコマンドを使用します。集約パイプライン。 mgo.v2 パッケージを使用した Go 実装は次のとおりです:

<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>

以上がGo を使用して MongoDB の複数の属性値に基づいて項目を取得する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。