skip to Main Content

There is a document that has a nested array inside a nested array. In one of the cases, I want to update the child array of child array.

    {
        "_id": "62da8472669b750870b094f6",
        "name": "Test Expert",
        "user_id": "62bdabee9aa50c0028d60767",
        "services": [
            {
                "service_name": "Hello 2",
                "service_id": "62ce7393534bda04d40f42c3",
                "_id": "62ce7394534bda04d40f42c4",
                "videos": [
                    {
                        "_id": "62da8472669b750870b094f8",
                        "lv_guid_id": "fsdfdshflsdhj",
                        "status": "REQUESTED" //Need to update this element status
                    },
 {
                        "_id": "62da8472669b750870b09sdw",
                        "lv_guid_id": "gdfgdfgfdg",
                        "status": "REQUESTED" //Need to update this element status
                    }
                ]
            }
        ],
        "__v": 0
    }

In this above document, I want to update the element inside videos array and this videos array are nested array of services array.

This is what I tried but I couldn’t get the second nested array position.

 this.findOneAndUpdate(
    { _id: new mongoose.Types.ObjectId(orderID), "services._id": new mongoose.Types.ObjectId(videoDetail.service_id), "services.videos.lv_guid_id": videoDetail.lv_guid_id },
    {
      $set: {
        "services.$.videos./*Need to fetch the position of this element to update*/.status": videoDetail.status
      }
    },
    { upsert: true, new: true }
  );

2

Answers


  1. All you have to do is "services.$.videos.$.status" if I get you right. Give it a try.

    this.findOneAndUpdate(
        {  _id: new mongoose.Types.ObjectId(orderID), "services._id": new mongoose.Types.ObjectId(videoDetail.service_id), "services.videos.lv_guid_id": videoDetail.lv_guid_id },
        { $set: { "services.$.videos.$.status": videoDetail.status } },
        { new: true },
    )
    
    Login or Signup to reply.
  2. You can use arrayFilters condition,

    • create a variable v and check the condition for lv_guid_id
    this.findOneAndUpdate(
      { 
        _id: new mongoose.Types.ObjectId(orderID), 
        "services._id": new mongoose.Types.ObjectId(videoDetail.service_id)
      },
      {
        $set: { "services.$.videos.$[v].status": videoDetail.status }
      },
      {
        arrayFilters: [{ "v.lv_guid_id": videoDetail.lv_guid_id }],
        upsert: true,
        new: true
      }
    )
    

    Playground

    Note: you can not upsert sub document/array element

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