Reputation: 57
I'm using $regex
in mongoose, a however a bit confused with its behavior.
Here's my data, I have one document which has one attribute "owner" as below.
{ "owner" : "lorem ipsum" }
now when I do search with {owner: {$regex:"",$options:"i"}}
in MongoDB compass it returns that object, and when I do {owner: ""}
, it returns nothing.
So can somebody explain to me why this behavior is like this, I do not have an empty string as an owner though while doing $regex
it returns that document.
Even I tried to remove space between lorem and "epsum" as "loremepsum" but it had the same behavior. Shouldn't it return same as {owner: ""}
?
Upvotes: 2
Views: 970
Reputation: 1879
{owner: {$regex: ""}}
this means find me nothing nothing, well there is nothing in your string which is in between letters
while this
{owner: ""}
means find me owner that's equal to this ""
i've tested your query in Robo 3T and i got the same results so i think it has to do with the regex version that mongo uses which is (PCRE-8.42)
Upvotes: 1
Reputation: 20747
I'm not a Mongoose expert by any means but it sounds like it's behaving correctly.
Basically, regexing for ""
results in a compiled regex that looks like //
which loosely translates to "find me nothing". This "nothing" exists anywhere that something does not exist so "nothing" exists between chars such as l
and o
of lorem
.
This can be best visualized using this code snippet:
echo preg_replace( '//', '8', 'lorem ipsum' );
which results in:
8l8o8r8e8m8 8i8p8s8u8m8
So Mongoose would be doing something like:
var_dump( preg_match( '//', 'lorem ipsum' ) );
which results in successfully finding "nothing"
In contrast {owner: ""}
would be looking for an absence of owner data.
Upvotes: 3