Suppose we have the following struct:
type shop struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Brands *brand `json:"brand,omitempty" bson:"brand,omitempty"`
}
type brand struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"deploymentid,omitempty"`
}
I tried to find a document using findOne()
but I don't get any document even there is a result match by using the MongoDB shell.
filter := bson.M{"brand" : bson.M{"_id" : someValue}}
var shopWithBrand shop
mycollection.findOne(ctx , filter).Decode(&shopWithBrand)
What mistake did I make?
This filter:
filter := bson.M{"brand" : bson.M{"_id" : someValue}}
Tells you want documents that have a brand
field that is an embedded document having a single _id
field whose value is the value of someValue
.
This would actually work if your embedded documents would only consist of this single _id
field, but your embedded brand
has this ID field mapped to deploymentid
and most likely has other fields as well (which you "stripped off" to minimize the example), and that is why it won't match.
Instead you want documents that have a brand
field being a document that has a matching deployment
field among other fields. This is how you can express that:
filter := bson.M{"brand.deploymentid" : someValue}