mongo-go-driver投影阵列长度

I'm trying to get a projection for the number of elements in a documents array.

options.SetProjection(bson.M{
    "foo": true,
    "nrOfBars": bson.M{ "$size": "$bars" },
})

bars is the fieldname of the array.
This query though always returns 0 instead of the arrays length.

How do I correctly query for the length of the array with the new mongo-go-driver?

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.