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

180
Visualizações
Get whole array by one of its strings. Array is inside another array. Mongodb/Javascript

In Mongodb if I have a structure like below, and I know the string let's say at vid > 0 > 0 how can I get the whole vid > 0 array returned? So that I can access also vid > 0 > 1 and vid > 0 > 2 ?

enter image description here

EDIT: db document structure:

...
updatedAt: 2021-01-17T16:44:28.824+00:00
vid: (Array)
  0: (Array)
    0: "adfsdfasfd"
    1: "this is some sample text"
    2: "https://example.com"
  1: (Array)
    0: "gfjghjhjgh"
    1: "this is another sample text"
    2: "https://example2.com"
...

So the question in regard to the text example above this time, is how do I get the whole Array 0 if I know the "adfsdfasfd" string?

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

0

Using aggregation query:

  • $match condition, put nested $ememMatch for 2 level condition
  • $reduce to iterate loop of vid array, set initial [], check condition if string in current array then return current array otherwise return initial value
let searchString = "adfsdfasfd";
db.collection.aggregate([
  {
    $match: {
      vid: { $elemMatch: { $elemMatch: { $in: [searchString] } } }
    }
  },
  {
    $addFields: {
      vid: {
        $reduce: {
          input: "$vid",
          initialValue: [],
          in: {
            $cond: [{ $in: [searchString, "$$this"] }, "$$this", "$$value"]
          }
        }
      }
    }
  }
])

Playground

Result:

[
  {
    "vid": [
      "adfsdfasfd",
      "this is some sample text",
      "https://example.com"
    ]
  }
]

Using find query:

  • Put match condition same as above
  • for projection get match result but in same nested array
let searchString = "adfsdfasfd";
db.collection.find(
  { vid: { $elemMatch: { $elemMatch: { $in: [searchString] } } } }
).project({ "vid.$": 1, _id: 0 }).toArray()

Playground

Result:

[
  {
    "vid": [
      [
        "adfsdfasfd",
        "this is some sample text",
        "https://example.com"
      ]
    ]
  }
]
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