首頁 > 後端開發 > Golang > 主體

如何使用 Go 在 MongoDB 中基於多個屬性值檢索項目?

DDD
發布: 2024-10-26 01:31:28
原創
385 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!