0
{ 
    "_id" : ObjectId("6221f3a818880f14e3c33040"), 
    "__v" : 0, 
    "createdAt" : ISODate("2022-03-04T11:10:32.753Z"), 
    "pm" : { 
        "checkList" : [ 
            { 
                "ch_id" : "621eff4e0ed5c751adaa42fb", 
                "status" : "statu", 
                "dateMonthYear" : 1646286480139.0, 
                "val" : "Gopi", 
                "remarks" : "Good", 
                "_id" : ObjectId("6221f3a80a703519a4406e6c") 
            }, 
            { 
                "ch_id" : "621eff4e0ed5c751adaa42fb", 
                "status" : "status", 
                "dateMonthYear" : 1646286480139.0, 
                "val" : "Gopi", 
                "remarks" : "Good", 
                "_id" : ObjectId("6221f3a80a703519a4406e6e") 
            } 
        ] 
    }, 
    "updatedAt" : ISODate("2022-03-04T11:56:59.662Z") 
}

Above is the collection, and in that I need to update the checklist array inside pm object using "_id" as a find condition. For example I need to change val and remarks of _id, ObjectId("6221f3a80a703519a4406e6e").

How to achieve this?

AlexisG
  • 2,476
  • 3
  • 11
  • 25
Manoj Shetty
  • 53
  • 2
  • 9
  • Does this answer your question? [MongoDB update data in nested field](https://stackoverflow.com/questions/19603542/mongodb-update-data-in-nested-field) – AlexisG Mar 04 '22 at 12:30
  • @AlexisG no, I need to update using the ObjectId within the element of checkList" array as condition ... Which is a nested object within PM... – Manoj Shetty Mar 04 '22 at 12:35
  • In the response of "Kanembel", he uses `arrayFilters` to update an array element based on a condition on this element – AlexisG Mar 04 '22 at 12:48
  • from what i understand OP doesnt know parentId but wants to update by childId – cmgchess Mar 04 '22 at 12:51
  • Yes I know that the question I linked differs from the question here, but the answer of "Kanembel" respond to the case here – AlexisG Mar 04 '22 at 13:03
  • Use the [`$ positional operator`](https://docs.mongodb.com/manual/reference/operator/update/positional/#update-documents-in-an-array) to update `Model.update({"pm.checkList._id":"6221f3a80a703519a4406e6e"},{"$set":{"pm.checkList.$.remarks":"Excellent","pm.checkList.$.val":"Tupi"}})` – chridam Mar 04 '22 at 14:16

2 Answers2

2
You can update a value in an array of nested objects in Mongoose

`db.users.update({"pm.checkList.ch_id" : "621eff4e0ed5c751adaa42fb"},{ $set:{
   "pm.checkList.$.val" : "nop",
   "pm.checkList.$.remarks" : "bed",
}})`
0

please try this way
using positional operation "$"

let collection = "deleted" db.getCollection(collection).findOneAndUpdate({"data._id":ObjectId("5f2c0ebd7493c812cf59c52c")},{"$set":{"data.$.isDefault" : false}},{new:true})

RONAK SUTARIYA
  • 546
  • 3
  • 11