Go : Aggregation : `$arrayElementAt`

I have not yet found in the Go driver docs anything that helps me understand how to use aggregation operators like $arrayElementAt that in JS take an array as an argument. Please help me correct my Go code.

Here is my aggregation pipeline in JS:

[{'$project': {'_id': false, 'potnum': true, 'first_image': {'$arrayElemAt': ['$images', 0]}}},
 {'$sort': {'potnum': 1}}, 
 {'$set': {'dirpath': '$first_image.dirpath', 'filename': '$first_image.filename'}}, 
 {'$project': {'dirpath': true, 'filename': true}}]

Here is how far I’ve gotten in Go but it dies with (InvalidPipelineOperator) Invalid $project :: caused by :: Unrecognized expression '$images'

	pip := mongo.Pipeline{
		{{"$project", bson.D{{"_id", false}, {"potnum", true}, {"first_image", bson.D{{"$arrayElemAt", bson.M{"$images": 0}}}}}}},
		{{"$sort", bson.D{{"potnum", 1}}}},
		{{"$set", bson.D{{"dirpath", "$first_image.dirpath"}, {"filename", "$first_image.filename"}}}},
		{{"$project",  bson.D{{"dirpath", true}, {"filename", true}}}}}

Found it on StackOverflow

This works:

pip := mongo.Pipeline{
		{{"$project", bson.D{{"_id", false}, {"potnum", true}, {"first_image", bson.M{"$arrayElemAt":[]interface{}{"$images", 0}}}}}},
		{{"$sort", bson.D{{"potnum", 1}}}},
		{{"$set", bson.D{{"dirpath", "$first_image.dirpath"}, {"filename", "$first_image.filename"}}}},
		{{"$project",  bson.D{{"dirpath", true}, {"filename", true}}}}}
1 Like

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