-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongostoragegroup.go
116 lines (102 loc) · 1.95 KB
/
mongostoragegroup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"context"
"fmt"
"sort"
"strconv"
"github.com/mongodb/mongo-go-driver/bson"
)
func (storage *MongoStorage) Group(query *AccountsGroupQuery) (result []map[string]interface{}, err error) {
context := context.Background()
match := bson.M{}
for field, value := range query.Filters {
switch field {
case "birth", "joined":
year, convErr := strconv.Atoi(value)
if convErr != nil {
err = &Error{400, fmt.Sprint("Bad", field, value)}
return
}
match[fmt.Sprint(field, "Year")] = year
case "likes":
likeeId, convErr := strconv.Atoi(value)
if convErr != nil {
err = &Error{400, fmt.Sprint("Bad like", value)}
return
}
likers := storage.likeeToLikerIndex.GetLikers(likeeId)
if likers != nil {
match["id"] = bson.M{
"$in": likers,
}
} else {
return
}
default:
match[field] = value
}
}
groupBy := bson.M{}
sortStage := bson.D{
{"count", query.Order},
}
for _, field := range query.Keys {
groupBy[field] = fmt.Sprint("$", field)
}
sort.Strings(query.Keys)
var unwindInterests = false
for _, field := range query.Keys {
sortStage = append(
sortStage,
bson.E{
fmt.Sprint("_id.", field),
query.Order,
},
)
if field == "interests" {
unwindInterests = true
}
}
pipeline := bson.A{
bson.M{
"$match": match,
},
}
if unwindInterests {
pipeline = append(
pipeline,
bson.M{
"$unwind": "$interests",
},
)
}
pipeline = append(
pipeline,
bson.M{
"$group": bson.M{
"_id": groupBy,
"count": bson.M{
"$sum": 1,
},
},
},
bson.M{
"$sort": sortStage,
},
bson.M{
"$limit": query.Limit,
},
)
cursor, findErr := storage.accounts.Aggregate(context, pipeline)
if findErr != nil {
err = &Error{500, findErr.Error()}
return
}
defer cursor.Close(context)
for cursor.Next(context) {
data := make(map[string]interface{})
cursor.Decode(&data)
result = append(result, data)
}
return
}