carsomyrxp
carsomyrxp

Reputation: 13

Dynamically create Aggregate pipeline for mongo-go-driver

https://godoc.org/github.com/mongodb/mongo-go-driver

I am trying to create an Aggregate pipeline dynamically. For example, I want to read a slice of string containing the oceans. I tried breaking these apart to pieces, but I could not find any methods to append elements.

pipeline := bson.NewArray(
    bson.VC.DocumentFromElements(
        bson.EC.SubDocumentFromElements(
            "$match",
            bson.EC.SubDocumentFromElements("ocean",
                bson.EC.ArrayFromElements("$in",
                    bson.VC.String("Pacific Ocean"),
                    //bson.VC.String("Indian Ocean"),
                ),
            ),
            bson.EC.SubDocumentFromElements("callTypeName",
                    bson.EC.ArrayFromElements("$in",
                        bson.VC.String("Wookie"),
                        bson.VC.String("Unknown 13"),
                    ),
            ),
        ),
    ),
)
cur, err := collection.Aggregate(context.Background(), pipeline)

Upvotes: 1

Views: 1019

Answers (1)

Leesa
Leesa

Reputation: 760

I thought the question was pretty clear, not sure if the first commentor was actually reading the statement carefully.

What this person was asking was to dynamically insert data given a list of data into the pipeline.

I had the same issue on a vue app my team and I are working on. Using your provided data, here is the general template:

Given a slice of string of oceans

a := []string{"Pacific Ocean", "Indian Ocean"}

Make a slice of size 0 of type *bson.Value

b := make([]*bson.Value, 0)

Loop through the slice of oceans and append bson converted values to slice b

for _, v := range a {
    b = append(b, bson.VC.String(v))
}

Then create key-value pair so that mongo can look for matches

c := bson.EC.ArrayFromElements("$in", b...)

Then pass c into the pipeline

pipeline := bson.NewArray(
    bson.VC.DocumentFromElements(
        bson.EC.SubDocumentFromElements(
            "$match",
            bson.EC.SubDocumentFromElements("ocean", c),
        ),
    ),
)

This should give you an idea on how to dynamically pipeline for callTypeNames

Upvotes: 2

Related Questions