Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda