Using bulkWrite with both $set and $setOnInsert on same keys

Viewed 431

I have the below code on my express server. Iam getting error:

errmsg: "Updating the path 'id' would create a conflict at 'id'",
    const bulkOps = productsAll.map((item) => {
      return {
        updateOne: {
          filter: { id: item.id },
          update: {
            $set: {
              id: parseInt(item.id),
              description: item.description,
              name: item.name,
              periodType: item.periodType,
              unitCost: item.unitCost,
              unitPrice: item.unitPrice,
              productBillingCodeID: parseInt(item.productBillingCodeID),
              newlyAdded: false,
            },
            $setOnInsert: {
              id: item.id,
              description: item.description,
              name: item.name,
              periodType: item.periodType,
              unitCost: item.unitCost,
              unitPrice: item.unitPrice,
              productBillingCodeID: item.productBillingCodeID,
              newlyAdded: true,
            },
          },
          upsert: true,
        },
      };
    });

What iam trying to do is insert new document if the id doesnt exist and update if exist. Also on each run of this code all updates should set newlyAdded to false and all inserts to set it to true.

Any pointers?

Thank you

1 Answers

You can use update with aggregation pipeline starting from MongoDB 4.2,

  • you can check $eq condition for newlyAdded field type is missing then update true otherwise false
const bulkOps = productsAll.map((item) => {
    return {
        updateOne: {
            filter: { id: item.id },
            update: [{
                $set: {
                    id: parseInt(item.id),
                    description: item.description,
                    name: item.name,
                    periodType: item.periodType,
                    unitCost: item.unitCost,
                    unitPrice: item.unitPrice,
                    productBillingCodeID: parseInt(item.productBillingCodeID),
                    newlyAdded: {
                        $eq: [{ $type: "$newlyAdded" }, "missing"]
                    }
                }
            }],
            upsert: true
        }
    };
});

Playground

Related