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

415
Visualizações
MongoDB v5.0.5 reference existing field in updateMany()

First time using MongoDB and I'm having an issue that I would appreciate some help with please.

Let's say I have a collection called "students" with documents in the collection structured as followed:

{
"_id": ObjectId("12345"),
"Name": "Joe Bloggs",
"Class_Grade": "b"
"Homework_Grade": "c",
}

I want to create an embedded document called "Grades" that contains the class and homework grade fields and applies this to every document in the collection to end up with:

{
"_id": ObjectId("12345"),
"Name": "Joe Bloggs",
"Class_Grade": "b"
"Homework_Grade": "c",
"Grades": {
    "Class_Grade": "b",
    "Homework_Grade": "c",
    }
}

I have been trying to achieve this using updateMany() in MongoShell:

db.students.updateMany({}, {$set: {Grades: {"Class_Grade": $Class_Grade, "Homework_Grade": $Homework_grade"}}})

However, in doing so, I receive Reference Error: $Class_Grade is not defined. I have tried amending the reference to $students.Class_Grade and receive the same error.

Your advice would be greatly appreciated

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

0

There are a few mistakes in your query,

  1. if you want to use the internal existing field's value, you need to use an update with aggregation pipeline starting from MongoDB 4.2, you need to wrap the update part in attay bracket [], as i added query.

  2. use quotation in field name that you want to use from internal field ex: "$Class_Grade"

  3. you have used field $Homework_grade, and in your documents it is G is capital in Grade so try to use exact field name $Homework_Grade

db.students.updateMany({},
[
  {
    $set: {
      Grades: {
        "Class_Grade": "$Class_Grade",
        "Homework_Grade": "$Homework_Grade"
      }
    }
  }
])

Playground

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