MongoDB updateOne multiple fields

Hi, I would like to update some fields by MongoDB.

sample of schema:

{
 id:1
 name: 'John',
 phone: {cell: 1234, work: 15345}, 
 grades: [
          { id: 'C1', grade: 5, q:1},
          { id: 'C2', grade: 6, q:1},
          { id: 'C3', grade: 3, q:2}
         ]
}

Change Input (find id=1 and change the name and grade with id=C2 and change only phone cell)

input = { 
          id:1, 
          name='Samanta', 
          phone: { cell: 2346},
          grades: { id:'C2', grade: 7}
}

Expected Result:

{
 id:1
 name: 'Samanta',
 phone: {cell: 2346, work: 15345}, 
 grades: [
          { id: 'C1', grade: 5, q:1},
          { id: 'C2', grade: 7, q:1},
          { id: 'C3', grade: 3, q:2}
         ]
}

Actually, I am looking to find a solution to merge the input and document by Ids (document and subdocument)
I appreciate any advice (it can be MongoDB or mongoose).

For setting the work phone something like

$set : { "phone.work" : 15435 }

should work.

For updating, one element of an array, I am pretty sure that you will need something like $map and $mergeObjects.

Hi @Mehran_Ishanian1 and welcome to the community forum!!

Further to @steevej’s suggestion, I experimented a little with your example document and arrive at this query:

 db.mongoose.updateOne({ "id": 1, "grades.id": "C2" }, { $set: { "grades.$.grade": 7, "phone.cell": 4566 , "name": "Samanta"} })
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
mongoose> db.mongoose.find()
[
  {
    _id: ObjectId("6350c1e16424749782987f72"),
    id: 1,
    name: 'Samanta',
    phone: { cell: 4566, work: 15345 },
    grades: [
      { id: 'C1', grade: 5, q: 1 },
      { id: 'C2', grade: 7, q: 1 },
      { id: 'C3', grade: 3, q: 2 }
    ]
  }
]

However, please note that the above command is based on the sample data provided above and has been tested on the latest mongoDB version 6.0.2 on mongosh
Please test the above on your environment based on the version and sample data in the collection.

Also, please note that, if there lies a possibility to alter the data at the application level and not on the database level.

Let us know if you have any further questions.

Best Regards
Aasawari

3 Likes

Thanks, steevej for your advice.

Dear @Aasawari Thanks for your warm welcome.
Thank you, it is working fine.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.