Actualy you will have many difficulties here if you stick with the regexp
aproach, I suggest you to create a text
index:
collection.createIndex({"users.name" : "text"});
And then when you will search:
db.collection('users').find({
$text: {
$search: params.query,
$caseSensitive: false,
}
});
In this way you will get the result when you use "Sagar", "sagar", "sagar gopa", "gopale sagar", and many combinations of those 2.
This aproach works very nicely if you have an autocomplete, or the client doesn't know exactly the name. Mongo dispose of strong text search algorithms that will match letters, even if they are not in proper order.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…