[英]How to do mongo aggregation
我正在尝试编写一个查询,它给出创建日期等于 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})
在 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.