skip to Main Content

I need to change a specific nested sub document field in the document status to true or false,

I know my schema is more nested but i don’t have any other option

this is my document model

{
"_id":"63b3b4024"
"name":"dev"
"email":"[email protected]"
"image":"https://sgp1.digitaloceanspaces.com"

"tickets":[
{
"sid":"63b3f5768"
"eid":"63b3f5777"
user_name:"john"
event_name:"workshop"
status:false
_id:{
"$oid":"63b4178c4"
}
},
{
"sid":"63b3f5769"
"eid":"63b3f5778"
"user_name":"john"
"event_name":"workshop"
"status":false
"_id":{
"$oid":"63b4178c5"
}
{
"sid":"63b3f5770"
"eid":"63b3f5779"
"user_name":"john"
"event_name":"workshop"
"status":false
"_id":{
"$oid":"63b4178c6"
}
{
"sid":"63b3f5771"
"eid":"63b3f5780"
"user_name":"john"
"event_name":"workshop"
"status":false
"_id":{
"$oid":"63b4178c7"
}
""__v":0
}]

I need to change tickests.status to true or false.How to check this field?

Can anyone suggest me the exact query to find this?

Specification

  • node: v14.17.3,

  • mongoose: "^6.6.5",

  • mongodb:Atlas

2

Answers


  1. If you need to update the status for a specific filter go with findOneAndUpdate:

    Model.findOneAndUpdate({ "tickets._id": <id-of-your-ticket}, { "tickets.$.status": <new-status-value> });
    
    Login or Signup to reply.
  2. you can use arrayFilters to identify the ticket you want to change the status of and use an update method as:

    await Collection.updateOne(
      { _id: collectionId },
      {
        $set: {
          "tickets.$[ticket].status": false,
        },
      },
      { arrayFilters: [{ "ticket._id": ticketId }] }
    );
    

    here, you identify the ticket you want by specifying the id in the arrayFilters as ticket._id, and you access this ticket in $set. Then, you change the status or any other field as required.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search