Array of unique object in document

Hi All,

I have the following code:

   const bulkOps = configItemsAll.map((item) => {
      return {
        updateOne: {
          filter: { id: item?.companyID },
          update: [
            {
              $set: {
                configItems: {
                  $setDifference: [
                    {
                      $concatArrays: [
                        { $ifNull: ['$configItems', []] },
                        [
                          {
                            id: item.id,
                            referenceNumber: item.referenceNumber,
                            referenceTitle: item.referenceTitle,
                            dateInstall: item.installDate,
                            newlyAdded: true,
                            status: {
                              active: {
                                state: item.isActive,
                              },
                              linked: {
                                state: {
                                  $ifNull: ['$configItems.status.linked.state', false],
                                },
                              },
                              ignored: {
                                state: {
                                  $ifNull: ['$configItems.status.ignored.state', false],
                                },
                              },
                              isMain: { $ifNull: ['$configItems.status.isMain', false] },
                            },
                          },
                        ],
                      ],
                    },
                    [],
                  ],
                },
              },
            },
          ],
          upsert: true,
        },
      };
    });

Company.bulkWrite(bulkOps, { ordered: true, writeConcern: { w: 1 } })

However, this will always fail after adding 19th item with:

 MongoBulkWriteError: BSONObj size: 25172982 (0x1801BF6) is invalid. Size must be between 0 and 16793600(16MB) First element: _id: ObjectId('6145dc3a22d9248f0fffc1c8')

All i want to do is to have a document with company details and each company has array of config items which is unique (no 2 items are same in this array by id field not others). each time script runs it will add item in the array if it doesnt exists or update if exists and differs on certain fields.

Could anyone help me please?

ok, so if i make it very simple :slight_smile: , ignore there is error happening.
How would i achieve the following:

  • script will run and adds to array in specific document if ID doesnt exist within this array or update if exists

i have tried $addToSet but this is for the whole object, problem is that object might change down the line