Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

410
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda