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

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

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 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