mongodb update array code example

Example 1: mongodb update field inside array

Consider the following document in the students collection whose grades element value is an array of embedded documents:

{
  _id: 4,
  grades: [
     { grade: 80, mean: 75, std: 8 },
     { grade: 85, mean: 90, std: 5 },
     { grade: 85, mean: 85, std: 8 }
  ]
}

Use the positional $ operator to update the std field of the first array element that matches the grade equal to 85 condition:

IMPORTANT
---------
You must include the array field as part of the query document.

db.students.updateOne(
   { _id: 4, "grades.grade": 85 },
   { $set: { "grades.$.std" : 6 } }
)
After the operation, the document has the following updated values:

{
   "_id" : 4,
   "grades" : [
      { "grade" : 80, "mean" : 75, "std" : 8 },
      { "grade" : 85, "mean" : 90, "std" : 6 },
      { "grade" : 85, "mean" : 85, "std" : 8 }
   ]
}

Example 2: mongodb replace item in array

db.movies.updateMany(
    { "languages": "French" }, 
    { "$set": { "languages.$": "Francais" } }
)

Example 3: how to update data subdocument array mongodb

// mongodb operation
db.getCollection('profilesservices').update({
  _id: ObjectId("6037ad8ac8f713f1d31abe38"), 
 "workExperience._id": ObjectId("6037ad8ac8f713f1d31abe39")}, 
   { $set: { "workExperience.$.companyName": "bukalapak" }
   
})


//sample data
}
    "profileId" : "Sa4Dq9Xuw",
    "photo" : "https://res.cloudinary.com/coding-street-art/image/upload/v1614261651/yxnvpazindsvz6lfst3m.jpg",
    "gender" : "pria",
    "birthDate" : ISODate("1997-03-19T17:00:00.000Z"),
    "status" : "mahasiswa",
    "nationality" : "indonesia",
    "aboutMe" : null,
    "resume" : "https://res.cloudinary.com/coding-street-art/raw/upload/v1614261653/bemkbknvhzknxffmala2.doc",
    "skills" : [ 
        "javascript", 
        "typescript", 
        "react", 
        "vuejs", 
        "express.js", 
        "nodejs"
    ],
    "userId" : "602e8f43c0e227e6cb80bc56",
    "workExperience" : [ 
        {
            "companyName" : "bukalapak", //before value is bukopin
            "jobPosition" : "data entry",
            "startDate" : ISODate("2015-02-14T17:00:00.000Z"),
            "endDate" : ISODate("2017-07-27T17:00:00.000Z"),
            "workInformation" : "",
            "_id" : ObjectId("6037ad8ac8f713f1d31abe39")
        }, 
        {
            "companyName" : "procar international finance",
            "jobPosition" : "general affair",
            "startDate" : ISODate("2015-02-14T17:00:00.000Z"),
            "endDate" : ISODate("2017-07-27T17:00:00.000Z"),
            "workInformation" : "",
            "_id" : ObjectId("507f1f77bcf86cd799439011")
        }
    ],
    "education" : [ 
        {
            "institutionName" : "unindra",
            "educationDegree" : "sarjana",
            "fieldStudy" : "tehnik informatika",
            "startDate" : ISODate("2015-03-24T17:00:00.000Z"),
            "endDate" : ISODate("2020-03-24T17:00:00.000Z"),
            "educationInformation" : "",
            "_id" : ObjectId("6037ad8ac8f713f1d31abe3a")
        }
    ],
    "appreciation" : [],
    "volunteerExperience" : [],
    "__v" : 0
}

Example 4: how to change array value mongodb

db.getCollection('profilesservices').updateOne({_id: ObjectId("603ce3bf9323e811c86cb7c8")}, {
 $set: {"jobPreferences.jobInterests.1": "backend developer"}    
})

## sample database
{
    "_id" : ObjectId("603ce3bf9323e811c86cb7c8"),
    "jobPreferences" : {
        "jobId" : "3c7d3c4c-756b-490f-b6ab-9c0992b120b3",
        "jobInterests" : [ 
            "frontend developer", 
            "devOps"
        ],
        "workTypes" : [ 
            "full-time", 
            "part-time", 
            "magang", 
            "freelance"
        ],
        "salaryExpectation" : 4500000,
        "workCityPreferences" : [ 
            "bandung", 
            "jakarta", 
            "bali"
        ]
    },

Tags:

Misc Example