Golang mongodb aggregation using mongo-driver

Viewed 857

I'm trying to perform the following Mongo query in Golang using mongo-driver:

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

How do I fix this?

1 Answers

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

Cheers

Related