Finding duplicates from collection .where keyid differ a bit

I have a collection name ACCOUNT where ABC-PQR-123-56789 is a key field.
each filed separated by “-” have some meaning and all together they make a unique combination.

Once the account is closed the key field is appended with open account date.
like ABC-PQR-123-56789-23062022 (eg. if it got closed today)

But for some reason account is created again ABC-PQR-123-56789 and hence there are 2 account for same id

ABC-PQR-123-56789 open
ABC-PQR-123-56789-23062022 closed

this should not happen and trying to find out how many such key id exist in my collection.
could you please help me to find such cases where one account is open and one closed with appended account open date.

Your problem is your kludge that modifies the account number.

Do you also modify documents from other collections that refer to this account? Ouch!

You should leave the account number unchanged and have closed_date field, period.

You should not have dates in the format DayMonthYear, use ISO-8601 date format YYYY-MM-DD.

I really do not see any other way that doing it with 3 trips to the DB.

  1. Make sure find( regex_of_account_number ) return no document
  2. Insert document with account_number
  3. Post insert verification to make sure 1. is still true, if false delete new document.