0

Please refer the following data structure that is stored in the database as a single document,

{
  "_id": "objectId",
  "names": [
    {
      "_id": "objectId",
      "first_name": "a",
      "is_used": {
        "hr": false,
        "finance": false
      },
      "alt_names": [
        {
          "_id": "objectId",
          "first_name": "b",
          "is_used": {
            "hr": false,
            "finance": false
          }
        }
      ]
    }
  ]
}

how can we update the alt_names hr: false to hr: true in nested object by using its object id

2 Answers2

0
const documents = [];
const targetDocumentId = "foo";

const targetDocument = documents.find(document => document._id === targetDocumentId);

const targetNameId = "bar";

const targetName = targetDocument.names.find(name => name._id === targetNameId);

if (targetName) {
  if (targetName.hasOwnProperty("alt_names")) {
    targetName.alt_names.is_used.hr = true;
  }
}
zr0gravity7
  • 2,917
  • 1
  • 12
  • 33
0

Your mongodb version should be at least 3.6, and code below is what you need.

db.collection.update(
    { "names.alt_names._id": "objectId" },
    { $set: { "names.$[].alt_names.$[filter].is_used.hr": true } },
    { arrayFilters: [{ 'filter._id': 'objectId' }] }
);

Reference are below.

Update an object in nested Array
MongoDB 3.6: Array Filters
Positional Operator Matching Nested Arrays

YuTing
  • 6,555
  • 2
  • 6
  • 16