• Home
  • Jobs
  • Courses
  • Teachers
  • For business
  • Blog
  • ES/EN

0

23
Views
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

13 days ago ·

Santiago Trujillo

1 answers
Answer question

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

13 days ago · Santiago Trujillo Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.