/
mongodb-bson2.go
53 lines (50 loc) · 1.28 KB
/
mongodb-bson2.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
//++++++++++++++++++++++++++++++++++++++++
// 《Go Web编程实战派从入门到精通》源码
//++++++++++++++++++++++++++++++++++++++++
// Author:廖显东(ShirDon)
// Blog:https://www.shirdon.com/
// 仓库地址:https://gitee.com/shirdonl/goWebActualCombat
// 仓库地址:https://github.com/shirdonl/goWebActualCombat
//++++++++++++++++++++++++++++++++++++++++
package main
import (
"context"
"fmt"
"gitee.com/shirdonl/goWebActualCombat/chapter4/mongodb"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"log"
)
func main() {
var (
client = mongodb.MgoCli()
collection *mongo.Collection
err error
cursor *mongo.Cursor
)
collection = client.Database("my_db").Collection("table1")
//按照jobName分组,countJob中存储每组的数目
groupStage := mongo.Pipeline{bson.D{
{"$group", bson.D{
{"_id", "$jobName"},
{"countJob", bson.D{
{"$sum", 1},
}},
}},
}}
if cursor, err = collection.Aggregate(context.TODO(), groupStage, ); err != nil {
log.Fatal(err)
}
defer func() {
if err = cursor.Close(context.TODO()); err != nil {
log.Fatal(err)
}
}()
var results []bson.M
if err = cursor.All(context.TODO(), &results); err != nil {
log.Fatal(err)
}
for _, result := range results {
fmt.Println(result)
}
}