简体   繁体   中英

mongo-go-driver projection array length

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM