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

176
Visualizações
MongoDB: Search for a string in a collection and return only matched collection items

I have the following json saved in the mongoDB:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "ID": "1753242",
        "TYPE": "8003"
      }
    },
    {
      "type": "Feature",
      "properties": {
        "ID": "4823034",
        "TYPE": "7005"
      }
    }
  ]
}

When i want to search for a specific TYPE, I can do it like this:

db.geo.find({"features.properties.TYPE":"8003"})

My problem is, that this query returns the whole json and not just elements with the TYPE "8003". Does anybody know, how to retrieve just elements with the TYPE "8003" by query?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

With the Mongo db 3.2 release, you can use the new $filter aggregation operator to filter an array during projection, which includes all the matches in the array

db.test.aggregate([
{$match: {'features': {$elemMatch : {"properties.TYPE": '8003' }}},
{$project: {
    features: {$filter: {
        input: '$features',
        as: 'feature',
        cond: {$eq: ['$$feature.properties.TYPE', '8003']}
    }}
}}
]);

If you just want the first element of the results, you can use the positional $ operator like below :

db.geo.find( { "features.properties.TYPE":"8003"}, { "features.$": 1 } )
over 4 years ago · Santiago Trujillo Relatório

0

$elemMatch operator returns only first element matching the $elemMatch condition in query result.

Please try executing following query

db.geo.find({
    features: {
        $elemMatch: {
            "properties.TYPE": "8003"
        }
    }
  }, {
    features: {
        $elemMatch: {
            "properties.TYPE": "8003"
        }
    }
  })

Please refer the documentation of $elemMatch operator as described in below mentioned URL

https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/

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