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

278
Visualizações
Mongoose find all documents that have a string in an array

I've a question:
How i can find all documents that have a string in an array using mongoose?

For example, my document:

<Model>.findMany(/* code that i need */).exec() // return all documents that have an array called "tags" that includes tag "test"
{
  "_id": {
    "$oid": "61b129b7dd0906ad4a2efb74"
  },
  "id": "843104500713127946",
  "description": "Server di prova",
  "tags": [
    "developers",
    "programming",
    "chatting",
    "ita"
  ],
  "shortDescription": "Siamo un server nato per chattare e aiutare programmatori su Discord!",
  "invite": "https://discord.gg/NdqUqHBxz9",
  "__v": 0
}

For example, if I need to get all documents with ita tag, I need to get this document. If the document doesn't have ita tag in array tag, I don't need it and the code will not return it.

Thanks in advance and sorry for bad english.

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

0

Actually you can just request tags to be test since mongoose looks for every tags entry

so this:

await Test.insertMany([{ tags: ["test"] }, { tags: ["Notest"] }])

let res = await Test.find({ "tags": "test" })
console.log(res)
    }

returns that:

[
  {
    _id: new ObjectId("61b8af02c3effad21a5d7187"),
    tags: [ 'test' ],
    __v: 0
  }
]

2 more neat things to know:

  1. This works no matter how many entries tags has, as long test is one of ethem
  2. This also enables you to change the entrie containing the "test" by using positional $ operator, so something like {$set: "tags.$": "smthNew"} will change all the test entries

Example for 2nd:

let res = await Test.updateMany({ "tags": "test" }, { $set: { "tags.$": "new" } }, { new: true })
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