简体   繁体   English

Golang mongodb 聚合使用 mongo-driver

[英]Golang mongodb aggregation using mongo-driver

I'm trying to perform the following Mongo query in Golang using mongo-driver:我正在尝试使用 mongo-driver 在 Golang 中执行以下 Mongo 查询:

var currentDate = ISODate("2021-01-22T00:00:00Z")
var someValue = "A"
db.someCollection.aggregate([
      {$match: {"data.date": currentDate, someAttribute: someValue}},
      {$project: {
          data: {$filter: {
              input: '$data',
              as: 'df',
              cond: {$eq: ['$$df.date', currentDate]}
          }},
          _id: 0
      }}
])

I have tried the following without much luck:我尝试了以下方法,但运气不佳:

currentDate := time.Date(2021, 1, 22, 0, 0, 0, 0, time.UTC)
someValue := "A"
matchStage := bson.D{{"$match", bson.D{{"data.date", currentDate}, {"someAttribute", someValue}}}}
projectStage := bson.D{{"$project", bson.D{{"data", bson.D{{"$filter", bson.D{{"input", "'$data'"}, {"as", "df"}, {"cond", bson.D{{"eq", bson.A{"$$df.date", currentDate}}}}}}}}}}}
                            
cur, err := someCollection.Aggregate(a.ctx, mongo.Pipeline{matchStage, projectStage})

Getting following error: input to $filter must be an array not string出现以下错误: input to $filter must be an array not string

How do I fix this?我该如何解决?

Answering my own question, it might be helpful for anyone facing this issue later.回答我自己的问题,这可能对以后遇到此问题的人有所帮助。

Here is what I did:这是我所做的:

currentDate := time.Date(2021, 1, 22, 0, 0, 0, 0, time.UTC)
someValue := "A"

matchStage := bson.D{{"$match", bson.D{{"data.date", currentDate}, {"someAttribute", someValue}}}}

projectStage := bson.D{
            {"$project", bson.D{
            {"_id", 0},
            {"data", bson.D{
                {"$filter", bson.D{
                    {"input", "$data"},
                    {"as", "df"},
                    {"cond", bson.D{
                        {"$eq", bson.A{"$$df.date", currentDate}},
                    }},
                }},
            },
        }},
    },
}

I added the _id also I removed the single quote around $data我添加了 _id 还删除了 $data 周围的单引号

Cheers干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM