You are trying to use an aggregation operator as part of the projection document. A projection document is for use in simple queries to only return certain fields.
What you want to use is the $project
stage in an aggregation pipeline. This is different from a simple projection document, and you are able to use more complex aggregation operators such as $size
. Here is some example code that I believe does what you would like:
ctx := context.TODO()
pipeline := bson.A{
bson.D{{
"$project",
bson.D{
{"foo", 1},
{"nrOfBars", bson.D{
{"$size", "$bar"},
}},
},
}},
}
cur, err := col.Aggregate(ctx, pipeline)
This aggregation returns a cursor. To access the results you must iterate through the cursor as described in the cursor documentation.