Search code examples
node.jsarraysmongodbmongooseembedded-documents

"$pull" doesn't delete the embedded documents of mongoose array


My mongo schema is as below:

resourceId: {
        type: String,
    },

    resourceName: {
        type: String,
    },

    dateAndValue: [
        {
            date: { type: Date },
            value: { type: Number },
        },
    ],

Once data is added to the "dateAndValue" array, I want to remove all objects in the array that includes '0' as the value. This is the code I used for it but it doesn't seem to work:

await QuantumResourcesManpowerAdmin.updateMany(
    { resourceId: qrmaRecord.resourceId },
    {
        $pull: {
            dateAndValue: {
                $elemMatch: { value: 0 },
            },
        },
    },
    { multi: true }
);

Solution

  • Found the answer, $elemMatch should be removed from the above code. So,

    await QuantumResourcesManpowerAdmin.update(
        { resourceId: qrmaRecord.resourceId },
        {
            $pull: {
                dateAndValue: {
                    value: 0,
                },
            },
        },
        { safe: true, multi: true }
    );
    

    would work without any issue