-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
75 lines (66 loc) · 1.67 KB
/
main.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
package main
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Example struct {
Type string `json:"type" bson:"type"`
CreatedAT time.Time `json:"created_at" bson:"created_at"`
Created int64 `json:"created" bson:"created"`
}
func main() {
uri := "mongodb://localhost:27017"
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
coll := client.Database("test").Collection("coll")
//coll.InsertOne(context.TODO(), &Example{
// Type: "B",
// CreatedAT: time.Now(),
// Created: time.Now().UnixNano(),
//})
//coll.InsertOne(context.TODO(), &Example{
// Type: "C",
// CreatedAT: time.Now(),
// Created: time.Now().UnixNano(),
//})
//coll.InsertOne(context.TODO(), &Example{
// Type: "B",
// CreatedAT: time.Now(),
// Created: time.Now().UnixNano(),
//})
//coll.InsertOne(context.TODO(), &Example{
// Type: "C",
// CreatedAT: time.Now(),
// Created: time.Now().UnixNano(),
//})
//coll.InsertOne(context.TODO(), &Example{
// Type: "B",
// CreatedAT: time.Now(),
// Created: time.Now().UnixNano(),
//})
cursor, err := coll.Find(context.TODO(), bson.M{}, options.Find().SetSort(
bson.M{"type": 1, "created": -1}))
if err != nil {
panic(err)
}
var examples []*Example
if err := cursor.All(ctx, &examples); err != nil {
panic(err)
}
for _, e := range examples {
fmt.Printf("%v\n", e)
}
}