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

190
Visualizações
Updating _id field in MongoDB

I want to update my _id field in one of the document ( shown below ).

{
_id : ObjectId("586d9d5d23352af1a4aa05f7"),
name: "Soham",
age : 99,
city : "XYZ"
}

So I ran the below steps:

var doc = db.names.find({name:"Soham"});
doc._id = 111 ; -- 111 is not present in that collection for any document
db.names.remove({_id:ObjectId("586d9d5d23352af1a4aa05f7")});
db.names.insert(doc);

The first 3 lines haven't threw any error, but the moment I ran the insert command, it threw error. Can anyone please let me know what's going wrong.

Thanks in advance!!!

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

0

Is throwing an error, because you can't update the _id field.

In order to set a new id, first you find the document (using findOne, since you search just for 1 document), than need to create a new document with new id and insert it, than we can safe delete the old:

var doc = db.names.find_one({name:"Soham"});
doc._id = 111 ; 
db.names.insert(doc);
db.names.remove({_id:ObjectId("586d9d5d23352af1a4aa05f7")});
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