Hello there,
I need to replace a string in an array field on multiple docs without creating duplicate values in the array.
Example documents:
{
_id: ObjectId('6284ea2cad10a6a1b43a7f53'),
bookingnr: 'BA-34567-3333-92540',
flags: ['direct', 'last-minute', 'family']
}
{
_id: ObjectId("628614db8e29fc2a5c8e4f0c"),
bookingnr: 'TA-87965-48521-89809',
flags: ['direct', 'reduced', 'external-booking', 'in-house']
}
What i came up with for now is:
db.collection.updateMany(
{ flags: 'direct' },
{ $set: { 'flags.$': 'in-house' } }
);
But this creates duplicate values when the value used in $set
is already part of the array. So how can I achieve this without duplicate array entries?
Further details/requirements:
- The solution should NOT throw an error on duplicates. Instead it should just not add it.
- I use mongoose for schemas, therefore a solution using pre/post hooks would also work for me.
cheers