Home > Enterprise >  MongoDB v5.0.5 reference existing field in updateMany()
MongoDB v5.0.5 reference existing field in updateMany()

Time:01-01

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

CodePudding user response:

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

  • Related