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

1.1K
Visualizações
MongoDB: Problems using $concat to update the value of a field

I'm trying to update the value of a field in a MongoDB collection by concatenating it with a literal string. Besides this, the field is an integer, and I want to add a "0" in front, so it will became a string.

I've read that I can't use the old value of the field in a single update instruction, so I'm using a forEach() method.

Here is the code:

db.col_1.find({"field_1": {$lt: 10000}}).forEach( function(i){
  db.col_1.update({_id: i._id},
    {$set: { "field_1": {$concat: ["0", i.field_1]}}} 
    )
});

The return result is :

The dollar ($) prefixed field '$concat' in 'field_1.$concat' is not valid for storage.

I'm sure I'm not writting the $concat command properly, is there any way to do this?

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

0

$concat is an aggregation pipeline, not an update operator/modifier.

It seems that what you're trying to do can be achieved by doing the following:

db.col_1
  .find({ "field_1": { $lt: 10000 } })
  .forEach( function(i) {
    db.col_1.update(
      { _id: i._id },
      { $set: { "field_1": "0" + i.field_1 } }
    )
   });
over 4 years ago · Santiago Trujillo Relatório

0

To update the MongoDB field using the value of another field for MongoDB version 4.2 also introduced the $set pipeline stage operator which is an alias for $addFields. You can use $set here as it maps with what we are trying to achieve.

let query = {
    "field_1": {
        $lt: 10000
    }
};
let changes = {
    $set: {
        "field_1": {
            "$concat": ["0", "$field_1"]
        }
    }
};
let UpdatedStatus = await col_1.updateMany(query, [changes]).lean();
console.log(UpdatedStatus);
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