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

329
Visualizações
MongoDb: add element to array if not exists

I'm using node.js and Mongo.db (I'm newly on Mongo). I have a document like this:

Tag : {
   name: string,
   videoIDs: array
}

The idea is, the server receives a JSON like

JSON: { 
    name: "sport",
    videoId: "34f54e34c"
}

with this JSON, it has to find the tag with the same name and check if in the array it has the videoId, if not, insert it to the array.

How can I check the array and append data?

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

0

You can use $addToSet operator to check exist before append element into array.

db.tags.update(
    {name: 'sport'},
    {$addToSet: { videoIDs: "34f54e34c" } }
);

In this update statement example, mongoDB will find the TAG document which matches name == sport, and then check whether the videoIDs array contains 34f54e34c. If not, append it to the array.

Detail usage of $addToSet please read here.

over 4 years ago · Santiago Trujillo Relatório

0

I didn't test it, but you can try something like:

yourDb.find({ name: "sport", 
              videoIDs: { $in: ["34f54e34c"] } })
      .update({$addToSet: { videoIDs: "34f54e34c" }});

If you need how: MongoDb in nodeJs implementation, you can start with:

http://jsfiddle.net/1ku0z1a1/

over 4 years ago · Santiago Trujillo Relatório

0

$addToSet operator check for the empty or existing array in document.

 db.col_name.update({name :"name_for_match"},{$addToSet :  { videoId : "video_id_value"}})
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