Update nested array element in mongodb

前端 未结 1 1575
情深已故
情深已故 2021-01-26 14:50

In my case I have mongodb document with nested arrays and I need to update attributes array elements. My mongodb document as follows.

{
\"_id\" : ObjectId(\"5dca         


        
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-26 15:08

    Couple of rectification required on the query, otherwise its almost there. The update is not working because $elemMatch for attributeSet (array of docs) field is to happen on id property of those docs to filter and not on attributeSet.id, it woudn't figure what it is. And nested elemMatch is not required, simply use dot notation.

    To debug you can try it out with a find query.

    Query (Shell):

    db.collection.findOneAndUpdate(
      {
        _id: settingsToBeUpdated._id,
        attributeSet: {
          $elemMatch: {
            id: attributeSetId,
            "attributes.id": id
          }
        }
      },
      {
        $set: {
          "attributeSet.$[as].attributes.$[a].attributeName":
            attributeDto.attributeName,
          "attributeSet.$[as].attributes.$[a].defaultValue":
            attributeDto.defaultValue,
          "attributeSet.$[as].attributes.$[a].isRequired": attributeDto.isRequired
        }
      },
      {
        arrayFilters: [{ "as.id": attributeSetId }, { "a.id": id }],
        returnNewDocument: true
      }
    );
    

    0 讨论(0)
提交回复
热议问题