1条记录(一个社区)的表示:
{
"_id" : ObjectId("538a4734d6194c0e98000001"),
"name" : "Darko",
"description" : "Darko",
"subdomain" : "darko",
"domain" : "forum.dev",
"created" : ISODate("2014-05-31T21:18:44.764Z"),
"category" : "Art and Culture",
"owner" : "53887456d6194c0f5b000001",
"members" : [
"53887456d6194c0f5b000001"
]
}
和 Go 类型
Community struct {
Id bson.ObjectId `bson:"_id,omitempty" json:"id"`
Name string `json:"name"`
Description string `bson:",omitempty" json:"description"`
Subdomain string `bson:",omitempty" json:"subdomain"`
Domain string `json:"domain"`
Created time.Time `json:"created"`
Category string `json:"category"`
Owner string `json:"owner"`
Banned []string `bson:",omitempty" json:"banned"`
Members []string `json:"members"`
Moderators []string `bson:",omitempty" json:"moderators"`
Admins []string `bson:",omitempty" json:"admins"`
Logo string `bson:",omitempty" json:"logo"`
Stylesheets []string `bson:",omitempty" json:"stylesheets"`
Javascripts []string `bson:",omitempty" json:"javascripts"`
}
好的,现在我想检索所有社区的列表,并按js 或GoCategory
Art and Culture
中的成员数量排序。members.length
len(Community.Members)
就像是SELECT * FROM communities ORDER BY COUNT(members) WHERE category = 'Art and Culture'
我有一个要填充或解组的自定义类型
CommunityDirectory struct {
Id bson.ObjectId `bson:"_id,omitempty" json:"id"`
Name string `json:"name"`
Description string `bson:",omitempty" json:"description"`
Subdomain string `bson:",omitempty" json:"subdomain"`
Domain string `json:"domain"`
Created time.Time `json:"created"`
Category string `json:"category"`
Logo string `bson:",omitempty" json:"logo"`
Membercount int64 `bson:"membercount" json:"membercount"`
}
到目前为止我所拥有的
func (ctx *CommunityContext) Directory() {
pipe := ccommunity.Pipe([]bson.M{bson.M{"membercount": bson.M{"$size": "members"}}})
iter := pipe.Iter()
result := CommunityDirectory{}
results := []CommunityDirectory{}
for {
if iter.Next(&result) {
results = append(results, result)
fmt.Println(result)
} else {
break
}
}
ctx.JSON(results)
}
但这不起作用,因为
db.communities.aggregate(
[
{"membercount": {$size:"members"}}
]
)
Error("Printing Stack Trace")@:0
()@src/mongo/shell/utils.js:37
([object Array])@src/mongo/shell/collection.js:866
@(shell):3
uncaught exception: aggregate failed: {
"errmsg" : "exception: Unrecognized pipeline stage name: 'membercount'",
"code" : 16436,
"ok" : 0
}
因此,它应该找到所有,按成员计数排序并分配一个新的“虚拟”字段成员计数,但仅限于“艺术和文化”类别。
我发现 MongoDB 在这方面相当复杂。
mongodb 查询是什么样的?
这在 Go/mgo 中是什么样子的?