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 학습자의 빠른 성장을 도와주세요!