首页 > 解决方案 > 如何做mongo聚合

问题描述

我正在尝试编写一个查询,它给出创建日期等于 365 的文档。我尝试了 mongo 指南针中的聚合,但不知道如何在 Go 中翻译它。以下是我在 mongo compass 中尝试过的内容

[{$project: {fileName:1,fileType:1,fileData:1,subtractDate: {$eq:[{$trunc:{$divide:[{$subtract:[newDate(),"$creationDate"]},1000*60*60*24]}},365]}}}]

从这里我创建了一个视图并将过滤器应用为 -{subtractDate:true}

以下是我的golang代码,请帮助我了解我在做什么错,因为错误即将到来 -missing ',' before newline in composite literal syntax

matchStage := bson.D{{"$match", bson.D{{}}}}
groupStage := bson.D{{"$project": bson.D{{"fileName": 1,"fileType": 1,"fileData": 1,"subtractDate":bson.D{{"$trunc": bson.D{{"$divide": []bson.D{{"$subtract": []time.Time{time.Date(),"$creationDate"}},1000 * 60 * 60 * 24}}}}}}}}}
myCollection  := client.Database("dbname").Collection("collectionName")
filterCursor2,err = myCollection.Aggregate(ctx,mongo.Pipeline{matchStage,groupStage})

标签: mongodbgoaggregation

解决方案


在 mongo 聚合中可以使用 golang 类型

agg := []map[string]interface{}{
        map[string]interface{}{
            "$project": map[string]interface{}{
                "fileName":1,
                "fileType":1,
                "fileData":1,
                "subtractDate": map[string]interface{}{
                    "$trunc": map[string]interface{}{
                        "$divide": []interface{}{
                            map[string]interface{}{
                                "$subtract": []interface{}{time.Now(), "$creationDate"},
                            },
                            1000*60*60*24,
                        },
                    },
                },
            },
        },
        map[string]interface{}{
            "$match": map[string]interface{}{
                "subtractDate": 365,
            },
        },
    }

只需将您的聚合选项放入您的集合的聚合方法

cur, err := DB.Collection("collectionName").Aggregate(context.TODO(), agg)
if err != nil {
    log.Println(err.Error())
}

然后获取结果

var result []map[string]interface{}
for cur.Next(context.TODO()) {
    var elem map[string]interface{}
    err := cur.Decode(&elem)
    if err != nil {
        log.Println(err.Error())
    } else {
        result = append(result, elem)
    }
}
if err := cur.Err(); err != nil {
    log.Println(err.Error())
}

log.Println(result)

推荐阅读