Search code examples
mongodbgomgo

mgo Ordered Sort Aggregation


I have the following code:

competitionMatch := bson.M{ "$match": bson.M{"competition" : bson.M{"$in" : []string{"PREMIERSHIP", "CHAMPIONSHIP", "LEAGUE1", "LEAGUE2"}}}}

group := bson.M{"$group" : bson.M{"_id" : "$homeTeam", "competitionOrder": bson.M{"$max": "$competitionOrder"}, "competition": bson.M{"$max" : "$competition"}}}
//sort := bson.M{"$sort" : bson.M{"competitionOrder": 1,"_id": 1}}
sort := bson.M{"$sort" : bson.D{{"competitionOrder", 1}, {"_id",1}}}
project := bson.M{"$project" : bson.M{"_id":1, "competitionOrder":1, "competition": 1}}

pipe := sessionCopy.DB("footballrecord").C(season).Pipe([]bson.M{competitionMatch, group, sort, project})

I'm trying to perform a sort. The commented sort works but as it is bson.M it is unordered, sometimes the query is not returning what I expect.

I'm trying to use bson.D (the uncommented line) but I get the following error when the query is run: the $sort key specification must be an object

Any idea where I'm going wrong?


Solution

  • I figured out this was an issue with godep. The import statements had not been rewritten.