[英]mongo-go-driver projection array length
I'm trying to get a projection for the number of elements in a documents array. 我正在尝试对documents数组中元素的数量进行投影。
options.SetProjection(bson.M{
"foo": true,
"nrOfBars": bson.M{ "$size": "$bars" },
})
bars
is the fieldname of the array. bars
是数组的字段名。
This query though always returns 0 instead of the arrays length. 尽管此查询始终返回0而不是数组长度。
How do I correctly query for the length of the array with the new mongo-go-driver? 如何使用新的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 . 您要使用的是聚合管道中的
$project
阶段。 This is different from a simple projection document, and you are able to use more complex aggregation operators such as $size
. 这与简单的投影文档不同,您可以使用更复杂的聚合运算符,例如
$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 .
要访问结果,您必须按照游标文档中所述遍历游标 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.