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

74
Vistas
Query to return a field from a nested json using MongoDB

My database has data in the following format :

{ "_id" : ObjectId( "abcd" ),
  "coordinate" : [somevalue, somevalue],
   "value" : [ 
   { "time" : 1,
     "characteristics" : "pqrs" },
   { "time" : 10,
     "characteristics" : "pqrs" }  ] }

I want to find the field closest coordinate and a time that is less than or equal to a given value.

Currently I'm using this query :

db.collection.aggregate({
    coordinate: {
        $geoNear: [latitude, longitude],
        $maxDistance: 10
    },
    "value.time": {
        $lte: 5
    }
})

This one returned the entire entry, but what I wanted is the field:

{ "time" : 1, "characteristics" : "pqrs" }

Is it even possible to just return this field ? What if there are multiple result and I just want the one that's closest to my value.time input ?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can perform an aggregation to :

  • $match items with specified coordinate and value.time
  • $filter value array to remove everything < 5
  • $unwind value array
  • $group by max value

Query is :

db.collection.aggregate({
    $match: {
        coordinate: {
            $geoNear: [0, 0],
            $maxDistance: 10
        },
        "value.time": {
            $lte: 5
        }
    }
}, {
    $project: {
        value: {
            $filter: {
                input: "$value",
                as: "value",
                cond: { $lte: ["$$value.time", 5] }
            }
        }
    }
}, {
    $unwind: "$value"
}, {
    $group: {
        _id: "$_id",
        time: { $max: "$value.time" },
        characteristics: { $first: "$value.characteristics" }
    }
})

Sample output :

{ "_id" : ObjectId("588a8c3080a14de2d654eb7b"), "time" : 4, "characteristics" : "pqrs" }
{ "_id" : ObjectId("588a89327fe89686fd2210b2"), "time" : 1, "characteristics" : "pqrs" }
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