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

1K
Vistas
How to apply multiple filters on mongodb collection based on user criteria using golang

From my frontend, users can apply filters based on date range or purpose, or both. How do i generate the MongoDB filter so that if users pass in date range, it only uses that as a filter? If it is only purpose, it only uses purpose and if it is both, it applies both filters. I am using golang. Here is my code

var filterData map[string]interface{}
if purpose != "" {
        filterData = bson.M{
            "purpose": purpose,
     }
var filterDate map[string]interface{}
if //condition for date range{
filterDate = bson.M{
        "paymentDate": bson.M{
            "$gte": startdate,
            "$lt":  enddate,
        },
}
}
//here i cant apply both
cursor, err = collection.Find(conn.DatabaseContext, findQuery)
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Use a single map for the filter (e.g. bson.M), and only add elements for filter conditions that the user supplied.

For example:

var purpose string
var startDate, endDate time.Time

filter := bson.M{}
if purpose != "" {
    filter["purpose"] = purpose
}
if !startDate.IsZero() && !endDate.IsZero() {
    filter["paymentDate"] = bson.M{
        "$gte": startDate,
        "$lt":  endDate,
    }
}

cursor, err = collection.Find(ctx, filter)
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