Mongo(Mgo) Pipe


(Sandeep Bhat) #1

Hi All

Wanted to know how do I access the result of a pipe aggregation of Mongo collections. The result is of type []bson.m{} as per all the examples or blogs I see online. On logging it I see the result as an array/slice of map with nested maps further. How do I extract it? I don’t see any examples regarding accessing the result to let us say map back the result values to some struct.

Thanks in advance.


(Sandeep Bhat) #2

The problem is how do you access fields of array of bson.m{} which in this case would be a map.


(Petko Petkov) #3

@sandyethadka,

Would you please post snippet of your code where you have the question? It would be easier for us to understand the exact problem.

This is good starting point on maps https://blog.golang.org/go-maps-in-action


(Sunny Karira) #4

TEST QUERY

type message struct {
	ID int64 `bson:"_id"`
	Size     int64 `bson:"size"`
}

func (e *ets) get(ctx context.Context, clientID int64) (int64, error) {
	sess := e.mgoSess.Copy()
	defer sess.Close()
	var result []*message
	pipeline := []bson.M{
		{
			"$match": bson.M{
				"id":   ID,
			},
		},
		{
			"$group": bson.M{
				"_id":       "null",
				"size": bson.M{"$sum": "$size"},
			},
		},
		{
			"$project": bson.M{
				"size": 1,
			},
		},
	}
	err := sess.
		DB("").
		C(collection).
		Pipe(pipeline).All(ctx, &result)
	if err != nil {
		err = errors.New("MongoDB find aggregation")
		return 0, err
	}
	if len(result) == 0 {
		return 0, nil
	}
	return result[0].Size, nil
}

(system) #5

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.