golang mongodb 分组sort 取第一个

usefull urls

https://blog.csdn.net/weixin_46124208/article/details/108483355

> db.sales.find()
{ "_id" : ObjectId("77f02ee61df85c423b6a4e79"), "client" : "1", "type" : "type1", "hierarchy" : "hier1", "creationDate" : ISODate("2015-09-09T13:06:44Z"), "model" : "m1" }
{ "_id" : ObjectId("77f02ee61df85c423b6a4e80"), "client" : "1", "type" : "type1", "hierarchy" : "hier1", "creationDate" : ISODate("2015-09-10T14:06:44Z"), "model" : "m2" }
{ "_id" : ObjectId("77f02ee61df85c423b6a4e81"), "client" : "1", "type" : "type1", "hierarchy" : "hier2", "creationDate" : ISODate("2015-09-10T13:06:44Z"), "model" : "m3" }
{ "_id" : ObjectId("77f02ee61df85c423b6a4e82"), "client" : "2", "type" : "type2", "hierarchy" : "hier2", "creationDate" : ISODate("2015-09-10T14:06:44Z"), "model" : "m4" }

//mongo 原始语句

db.sales.aggregate([
{$match:{$or:[{"client":"1"},{"client":"2"}]}},
{$sort:{"creationDate":1}},
{$group:{"_id":{"hierarchy":"$hierarchy"},"record":{$first:"$$ROOT"}}},
{$project:{"_id":"$record._id","client":"$record.client","hierarchy":"$record.hierarchy","creationDate":"$record.creationDate"}}
]);
 1 package main
 2 
 3 import (
 4     "context"
 5     "fmt"
 6     "strings"
 7     "time"
 8 
 9     "go.mongodb.org/mongo-driver/bson"
10     "go.mongodb.org/mongo-driver/mongo"
11     "go.mongodb.org/mongo-driver/mongo/options"
12 )
13 
14 
15 func MongoPipeline(str string) mongo.Pipeline {
16     var pipeline = []bson.D{}
17     str = strings.TrimSpace(str)
18     if strings.Index(str, "[") != 0 {
19         var doc bson.D
20         bson.UnmarshalExtJSON([]byte(str), false, &doc)
21         pipeline = append(pipeline, doc)
22     } else {
23         bson.UnmarshalExtJSON([]byte(str), false, &pipeline)
24     }
25     return pipeline
26 }
27 
28 func main() {
29     ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
30     client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://1.1.13.10:27017"))
31     if err != nil {
32         panic(err)
33     }
34     defer client.Disconnect(ctx)
35 
36     database := client.Database("huzh")
37     episodesCollection := database.Collection("sales")
38     opts := options.Aggregate()
39     //id, _ := primitive.ObjectIDFromHex("5e3b37e51c9d4400004117e6")
40     //
41     //matchStage := bson.D{{"$match", bson.D{{"podcast", id}}}}
42     //groupStage := bson.D{{"$group", bson.D{{"_id", "$podcast"}, {"total", bson.D{{"$sum", "$duration"}}}}}}
43 
44     //id, _ := primitive.ObjectIDFromHex("5e3b37e51c9d4400004117e6")
45 
46 
47 //    pipeline := `
48 //[
49 //{$match:{$or:[{"client":"1"},{"client":"2"}]}},
50 //{$group:{"_id":{"hierarchy":"$hierarchy"},"record":{$first:"$$ROOT"}}},
51 //{$project:{"_id":0}}
52 //]`
53 
54 var rb []bson.M
55     rb = []bson.M{bson.M{"client": "1"}, bson.M{"client": "2"}}
56     fmt.Println(rb)
57     pipeline := mongo.Pipeline{
58         bson.D{
59             {"$match", bson.M{"$or":rb}},
60             //{"$match", bson.M{"$or":[]bson.M{bson.M{"client": "1"}, bson.M{"client": "2"}}}},
61         },
62         bson.D{
63             {"$sort", bson.D{{"creationDate", -1}}},
64         },
65         bson.D{
66             {"$group", bson.D{
67                 //{"_id", "$betarea"},
68                 //{"sum", bson.D{{"$sum", "$amount"}}},
69                 //{"count", bson.D{{"$sum", 1}}},
70                 {"_id", bson.D{{"hierarchy", "$hierarchy"}}},
71                 {"record", bson.D{{"$first", "$$ROOT"}}},
72             }},
73         },
74         bson.D{
75             {"$project", bson.M{"_id":"$record._id","client":"$record.client","hierarchy":"$record.hierarchy","creationDate":"$record.creationDate"}},
76         },
77 
78 
79     }
80 
81     //showInfoCursor, err := episodesCollection.Aggregate(ctx,  MongoPipeline(pipeline),opts)
82     showInfoCursor, err := episodesCollection.Aggregate(ctx,  pipeline,opts)
83     //fmt.Println(showInfoCursor)
84     if err != nil {
85         panic(err)
86     }
87     var showsWithInfo []bson.M
88     if err = showInfoCursor.All(ctx, &showsWithInfo); err != nil {
89         panic(err)
90     }
91     fmt.Println(showsWithInfo)
92     fmt.Println(len(showsWithInfo))
93 }
原文地址:https://www.cnblogs.com/eiguleo/p/13925954.html