hss
hss

Reputation: 75

How to do mongo aggregation

I am trying to write a query which gives out documents where creationDate is equal to 365. I tried the aggregation in the mongo compass, but not sure how to translate it in Go. Below is what I have tried in mongo compass

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

From this i created a view and applied filter as - {subtractDate:true}

Below is my golang code , pls help me as to what wrong am i doing as error coming - 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})

Upvotes: 0

Views: 190

Answers (1)

Rostyslav
Rostyslav

Reputation: 176

In mongo aggregation it is possible to use golang types

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,
            },
        },
    }

Just put your aggregation options to Aggregate method of your collection

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

And then fetch result

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)

Upvotes: 1

Related Questions