【问题标题】:Golang mongodb aggregation using mongo-driverGolang mongodb 聚合使用 mongo-driver
【发布时间】:2021-04-28 17:13:08
【问题描述】:

我正在尝试使用 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
      }}
])

我尝试了以下方法,但运气不佳:

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

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

我该如何解决这个问题?

【问题讨论】:

    标签: mongodb go


    【解决方案1】:

    回答我自己的问题,这可能对以后遇到此问题的人有所帮助。

    这是我所做的:

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

    我添加了 _id 并删除了 $data 周围的单引号

    干杯

    【讨论】:

    • 我得到 2 个结果,但无法使用 all 方法返回第一个结果。最后一个是空的
    猜你喜欢
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 2021-11-14
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    • 2019-02-01
    相关资源
    最近更新 更多