mongodb - 如何做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})
解决方案
在 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)
推荐阅读
- javascript - wp_login_form() 锚点动态重定向
- visual-studio-code - 不能在 C 文件中包含任何内容,vs 代码
- swift - 如何在 SwiftUI 中更改分段选取器的颜色外观?
- pandas - Python pymannkendall 和 Pandas Groupby 解包结果
- corda - Corda - 即使使用通过 QuerybyAccount 查找令牌的相同查询,RedeemFungibleTokens 也会给出“可用状态不足”
- macos - DriverKit 系统扩展可以在启动时匹配热插拔设备吗?
- multidimensional-array - Julia - 使用 mvNormal 生成具有给定均值和协方差矩阵的多元高斯样本
- visual-studio-code - 如何增加 VS CODE 内存使用率
- python - 使用 *args 定义 Python 类成员函数
- c# - 防止子元素的事件以 MVVM 方式冒泡到其父元素