1Consider the following document in the students collection whose grades element value is an array of embedded documents:
2
3{
4 _id: 4,
5 grades: [
6 { grade: 80, mean: 75, std: 8 },
7 { grade: 85, mean: 90, std: 5 },
8 { grade: 85, mean: 85, std: 8 }
9 ]
10}
11
12Use the positional $ operator to update the std field of the first array element that matches the grade equal to 85 condition:
13
14IMPORTANT
15---------
16You must include the array field as part of the query document.
17
18db.students.updateOne(
19 { _id: 4, "grades.grade": 85 },
20 { $set: { "grades.$.std" : 6 } }
21)
22After the operation, the document has the following updated values:
23
24{
25 "_id" : 4,
26 "grades" : [
27 { "grade" : 80, "mean" : 75, "std" : 8 },
28 { "grade" : 85, "mean" : 90, "std" : 6 },
29 { "grade" : 85, "mean" : 85, "std" : 8 }
30 ]
31}
1db.collectionName.update({"aField":"vale1"},{$set:{"anotherField":"value2"}})
2
3-search for documentations for more examples than search
4-aField is used to find the documents
5-anotherField is the field that will be updated
6-You can also use the below:
7-- updateOne
8-- findOneAndUpdate
1const query = { "name": "football" };
2const update = {
3 "$push": {
4 "reviews": {
5 "username": "tombradyfan",
6 "comment": "I love football!!!"
7 }
8 }
9};
10const options = { "upsert": false };
11
12itemsCollection.updateOne(query, update, options)
13 .then(result => {
14 const { matchedCount, modifiedCount } = result;
15 if(matchedCount && modifiedCount) {
16 console.log(`Successfully added a new review.`)
17 }
18 })
19 .catch(err => console.error(`Failed to add review: ${err}`))
20