1
{ 
    "_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?

6
  • Does this answer your question? MongoDB update data in nested field Commented Mar 4, 2022 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... Commented Mar 4, 2022 at 12:35
  • In the response of "Kanembel", he uses arrayFilters to update an array element based on a condition on this element Commented Mar 4, 2022 at 12:48
  • from what i understand OP doesnt know parentId but wants to update by childId Commented Mar 4, 2022 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 Commented Mar 4, 2022 at 13:03

2 Answers 2

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",  
}})
Sign up to request clarification or add additional context in comments.

Comments

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})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.