Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
887 views
in Technique[技术] by (71.8m points)

go - Golang mongodb aggregation using mongo-driver

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?

question from:https://stackoverflow.com/questions/65875604/golang-mongodb-aggregation-using-mongo-driver

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...