Delete all documents from a collection based on a condition and create missing ones
You can do it in following steps:
Delete all the documents in the collection whose
Name
field's value is present in theconfig
array.To delete any document whose
Name
field's value is not in theconfig
array, write a delete query using$in
and$not
operators.UIConfiguration.deleteMany({ Name: { $not: { $in: ["Name1", "Name2"] } } });
Fetch all the documents whose
Name
field's value exists in theconfig
array. You can do this using$in
operatorUIConfiguration.find({ Name: { $in: ["Name1", "Name2"] } });
Iterate over the returned array of documents and filter out those name strings in
config
array that do not match any document'sName
field value.Finally, insert all the names in the filtered array in the collection using
.insertMany
methodUIConfiguration.insertMany([/* filtered name objects */]);
For further details on methods and operators used above, see: