Home > OS >  unable to update a subdocuments in an array
unable to update a subdocuments in an array

Time:11-30

im trying to update a value for uid in solts.slots but nothing works. i want to iterate two level of array to modify the document

{
"_id": {
  "$oid": "638455dee12f0122c9812697"
},
"bid": "637b0fdd3d9a96eb913805d3",
"name": "sucess",

"slots": [
  {
    "date": "2022-11-28T00:00:00.000Z",
    "slots": [
      
      {
        "uid": null,
        "available": true,
        "status": null,
        "_id": {
          "$oid": "638455dee12f0122c98126a0"
        }
      },
      {
        "uid": null,
        "available": true,
        "status": null,
        "_id": {
          "$oid": "638455dee12f0122c98126a1"
        }
      }
      
    ],
    "_id": {
      "$oid": "638455dee12f0122c9812698"
    }
  }   
    ]}]}
    

im trying to update the slots for id 638455dee12f0122c98126a0 properties like

  • uid:'234235'
  • available:false
  • status:'booked'

can anyone help me to query this

i tried

const result = await Event.findOne({
        'slots.slots': {
            $elemMatch: {
                _id: req.body.id
            }
        }
    })

is there is any way to query this type of documents.

CodePudding user response:

You can use $[] and $[<identifier>]:

db.collection.update({
  "slots.slots": {
    $elemMatch: {
      _id: ObjectId("638455dee12f0122c98126a0")
    }
  }
},
{
  $set: {
    "slots.$[].slots.$[item].available": false,
    "slots.$[].slots.$[item].uid": "234235",
    "slots.$[].slots.$[item].status": "booked"
  }
},
{
  arrayFilters: [
    {
      "item._id": ObjectId("638455dee12f0122c98126a0")
    }
  ]
})

See how it works on the playground example

  • Related