Mongo: 4.4 Go: 1.17.3
I'm trying to get documents with string field value longer than four symbols. Here is the query I use inside mongo's shell:
db.player.find({
"name": { "$exists": true },
"$expr": { "$gt": [ { "$strLenCP": "$name" }, 4 ] }
})
And here is the same query but coded as bson filter in go:
longName := bson.M{
"name": bson.M{"$exists": true},
"$expr": bson.M{
"$gt": bson.A{
bson.M{"$strLenCP": "$name"},
4,
},
},
}
fmc, err := collection.Find(context.TODO(), longName)
if err != nil {
log.Panic(err)
}
var longBoi models.Player
err = fmc.Decode(&longBoi)
if err != nil {
log.Panic(err)
// panic here:
// 2021/12/15 15:53:46 EOF
// panic: EOF
}
The first will output desired documents with string field value length longer than certain number. The second will error with just EOF, timestamp and callstack. Debugger says that batch inside coursor fmc contains no data.
What's wrong in the second case?
The following fixes the problem:
var longBoi []models.Player
err = fmc.All(context.TODO(), &longBoi)
if err != nil {
log.Panic(err)
}
Find() returns the Cursor(), not the documents. The cursor then can be used to iterate over documents matching the filter by calling All() or some other method.