Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda