2
showInfoCursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{unwindStage, groupStage})
    if err != nil {
        panic(err)
    }
    var showsWithInfo []bson.M
    if err = showInfoCursor.All(context.TODO(), &showsWithInfo); err != nil {
        panic(err)
    }

I'm iterating the showsWithInfo array. And each bson.M contains a primitive M type value for a particular key. I've tried to convert it to a struct, but it was no successful.

map[operatorId:1 channel: XYZ]

This is what I got once I print the value of that primitive M. I need to get those two values from that. (operatorId, channel)

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
G. Raven
  • 77
  • 8

1 Answers1

3

bson.M is a type alias to primitive.M:

type M = primitive.M

And primitive.M is a "simple" map:

type M map[string]interface{}

So you may index the value as you would any maps:

m := primitive.M{
    "operatorId": 1,
    "channel":    "XYZ",
}
fmt.Println(m)

fmt.Println("Operator ID:", m["operatorId"])
fmt.Println("Channel:", m["channel"])

This outputs (try it on the Go Playground):

map[channel:XYZ operatorId:1]
Operator ID: 1
Channel: XYZ
icza
  • 389,944
  • 63
  • 907
  • 827