Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
Mongo filter works inside the mongo shell but doesn't work when written in go

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!