Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice to check if document with field value exists in MongoDB?

Tags:

regex

php

mongodb

I was wondering what is the best practice to check if username is already registered. For example I sign up as Peter and I want to prevent other users from using:

  • PETER
  • pETER
  • peter
  • PEteR
  • peTeR

you've got the idea. Should I use regex for case-insensitive query using MongoDB in PHP:

$username = 'Peter';
$db->users->count(['username' => new MongoDB\BSON\Regex('^'.$username.'\\b', 'i')]);

or should I store 2 versions of username, the original version and one lower case version for this purpose?

$username = strtolower('Peter');
$query = $db->users->count(['username_lowercase' => $username]);
if ($query > 0) {
    echo 'This username is already used';
}

or is there any other approach?

like image 201
Peter Bielak Avatar asked Dec 20 '25 11:12

Peter Bielak


1 Answers

Regarding performance, the best approach is always to test and never have prejudice.

A third approach would be to use a case insensitive index with unique constraint. See https://docs.mongodb.com/manual/core/index-case-insensitive/ and oh I've found a duplicate of your question how to index a username in mongo with case-insensitively?

like image 177
Benjamin Toueg Avatar answered Dec 23 '25 01:12

Benjamin Toueg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!