0
I have users collection with these documents.
[
    {
        email:'[email protected]'
    },{
        email:'[email protected]',
    },{
        email:'[email protected]',
    },{
        email:'[email protected]',
    },{
        email:'[email protected]',
    }
]
I want to search users with partial email or full email like ex--
req.body.email='abc+2345';//partial search
let email = req.body.email;
req.body.email='[email protected]';//full email search

Mongo query to search partial or full using Regx

Users.find({$or:[{ 'email': { $regex: email, '$options': 'i' }}]})

It is unable to find users whose email contain 'abc+2345' or '[email protected]'.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
sameer
  • 19
  • 3

2 Answers2

0

We need to escape '+' in the regex. The following query can also get you the expected output:

db.check.find({"email":/abc\+2345/i}).pretty()

Output:

{
    "_id" : ObjectId("5d4a4735cbfa696dcd99249f"),
    "email" : "[email protected]"
}
{
    "_id" : ObjectId("5d4a4735cbfa696dcd9924a0"),
    "email" : "[email protected]"
}
{
    "_id" : ObjectId("5d4a4735cbfa696dcd9924a1"),
    "email" : "[email protected]"
}
{
    "_id" : ObjectId("5d4a4735cbfa696dcd9924a2"),
    "email" : "[email protected]"
}
Himanshu Sharma
  • 2,940
  • 1
  • 7
  • 18
0

do it like this

MongoDB Enterprise > db.user.find({$or :[{ email: { $regex: /^abc\+2345/ ,$options :'i'} },{email:"[email protected]"}]})
{ "_id" : ObjectId("5d4a477dd72dc9d0a4b71d85"), "email" : "[email protected]" }
{ "_id" : ObjectId("5d4a477dd72dc9d0a4b71d86"), "email" : "[email protected]" }
{ "_id" : ObjectId("5d4a477dd72dc9d0a4b71d87"), "email" : "[email protected]" }
{ "_id" : ObjectId("5d4a477dd72dc9d0a4b71d88"), "email" : "[email protected]" }
{ "_id" : ObjectId("5d4a4b67d72dc9d0a4b71d89"), "email" : "[email protected]" }
MongoDB Enterprise > 

in $or the first stage is with regex ,second used for full match

HbnKing
  • 1,762
  • 1
  • 11
  • 25