Delete all documents from a collection based on a condition and create missing ones Delete all documents from a collection based on a condition and create missing ones mongoose mongoose

Delete all documents from a collection based on a condition and create missing ones


You can do it in following steps:

  1. Delete all the documents in the collection whose Name field's value is present in the config array.

    To delete any document whose Name field's value is not in the config array, write a delete query using $in and $not operators.

    UIConfiguration.deleteMany({ Name: { $not: { $in: ["Name1", "Name2"] } } });
  2. Fetch all the documents whose Name field's value exists in the config array. You can do this using $in operator

    UIConfiguration.find({ Name: { $in: ["Name1", "Name2"] } });
  3. Iterate over the returned array of documents and filter out those name strings in config array that do not match any document's Name field value.

  4. Finally, insert all the names in the filtered array in the collection using .insertMany method

    UIConfiguration.insertMany([/* filtered name objects */]);  

For further details on methods and operators used above, see: