MongoDB aggregation pipeline with go-driver returning empty result

Hi Folks , I have the following Issue while performing a aggregation with $in clause

The data looks like this

{"PINCODE" : 500081, "CITY" : "CITY_001",  "status" : "PUBLISHED", "version:" : 0},
{"PINCODE" : 500081, "CITY" : "CITY_001",  "status" : "DRAFT", "version:" : 1},
{"PINCODE" : 481001, "CITY" : "CITY_002",  "status" : "DRAFT", "version:" : 0},

Query which i am trying to achieve
I am trying to find out the latest version for each PINCODE , so the first step which i am applying is a match stage where we will match multiple PINCODE

  { $match : { PINCODE : { $in : [500081, 481001] }} },

The above query is giving proper result but when i am trying to do the same in golang code it doesn’t return any value , sample code

matchStage := bson.D{{Key: "$match", Value: bson.E{Key: "PINCODE", Value: bson.E{Key: "$in", Value: []interface{}{500081, 481001}}}}}
cursor, err := collection.Aggregate(ctx, mongo.Pipeline{matchStage})

The above query returns 0 results ,

Pls ket me know whats the correct way to get the above query in golang driver

Hey @Nitish_Bhagat,

Welcome to the MongoDB Communtiy forums :sparkles:

I believe you can use $group to find the latest version of each PINCODE. In this case, you won’t need to pass all the PINCODEs to the $in clause. Please let me know if I missed anything relevant to your question.

db.collection.aggregate([ { 
                    $group: { _id: "$PINCODE", 
                              latestVersion: { $max: "$version" } } }] )

You can convert the same query to Golang driver code:

import (

                {"_id", "$PINCODE"},
                {"latestVersion", bson.D{{"$max", "$version"}}},

In addition to it you can use Export to Language feature of MongoDB Compass to convert your queries created in the query bar to one of the supported languages.

Let us know if you have any further question.

Best regards,