0

Mongodb query:

db.products.aggregate([
    { 
        $match : { 
           "_id" : ObjectId("60d95b5ab861ccc04fd4b598") 
        }
    },  
    { 
        $project: {
            title : "Test Product 10", 
            offers: { 
                $filter: {
                    input: "$offers", 
                    as: "offers",
                    cond: { 
                        $eq: [ "$$offers.active", true ]
                    }
                }
            }
        }
    }
]).pretty()

Golang Query:

productMatch := bson.D{{"$match", bson.M{"_id": objID}}}
project := bson.D{{"$project", bson.D{{"offers", bson.D{{"$filter", bson.D{{
        "input", "$offers"}, {"as", "offers"}, {"cond", bson.D{{
        "$eq", bson.D{{"$$offers.active", true}}}}}}}}}}}}
pipeLine := mongo.Pipeline{productMatch, project}
result, err := s.DB.Collection(collectionProducts).Aggregate(context.TODO(), pipeLine)
icza
  • 389,944
  • 63
  • 907
  • 827
  • 1
    Can you please add the full error message. – Jens Jun 29 '21 at 12:17
  • Youi don't need `cond: { $eq: [ "$$offers.active", true ] }`. Using just `cond: "$$offers.active"` should be sufficient. – Wernfried Domscheit Jun 29 '21 at 12:19
  • @Jens ERROR product/service.go:63 Error getting product {"error": "(InvalidPipelineOperator) Invalid $project :: caused by :: Unrecognized expression '$$offers.active'", "id": "60d18c90dcb548b79b898da8"} – Nithin Urs Jun 30 '21 at 02:25

1 Answers1

1

This part:

cond: { 
    $eq: [ "$$offers.active", true ]
}

The value for $eq is an array. bson.D is to model documents. To model an array, use bson.A.

So instead of:

{"cond", bson.D{{
    "$eq", bson.D{{"$$offers.active", true}}}}}

Use

{"cond", bson.D{{
    "$eq", bson.A{"$$offers.active", true}}}}
icza
  • 389,944
  • 63
  • 907
  • 827
  • error message: ```product/service.go:63 Error getting product {"error": "EOF", "id": "60d18c90dcb548b79b898da8"}``` – Nithin Urs Jun 30 '21 at 02:31
  • @NithinUrs Please update your question and describe the code that you used to test icza's proposed answer. Also add the error that you got. – Jens Jun 30 '21 at 07:17
  • @NithinUrs I tried the solution I posted and it worked for me. If it doesn't work for you, please provide a [mcve]. – icza Jun 30 '21 at 07:33