Mongoose text-search with partial string Mongoose text-search with partial string mongodb mongodb

Mongoose text-search with partial string


regex can help you with this.

Person.find({ "name": { "$regex": "Alex", "$options": "i" } },function(err,docs) { });


You can do this with an aggregate pipeline that concatenates the first and last names together using $concat and then searches against that:

let regex = new RegExp(QUERY,'i');Person.aggregate([    // Project the concatenated full name along with the original doc    {$project: {fullname: {$concat: ['$name.first', ' ', '$name.last']}, doc: '$$ROOT'}},    {$match: {fullname: regex}}], function(err, persons) {    // Extract the original doc from each item    persons = persons.map(function(item) { return item.doc; });    console.log(persons);});

Performance is a concern, however, as this can't use an index so it will require a full collection scan.

You can mitigate that by preceding the $project stage with a $match query that can use an index to reduce the set of docs the rest of the pipeline needs to look at.

So if you separately index name.first and name.last and then take the first word of your search string as an anchored query (e.g. /^John/i), you could prepend the following to the beginning of your pipeline:

{$match: $or: [  {'name.first': /^John/i},  {'name.last': /^John/i}]}

Obviously you'd need to programmicatically generate that "first word" regex, but hopefully it gives you the idea.


a). Partial Text Search in a single field in collection :

If we want to search in single field in collection we can use that code in aggregate

{  $match: {    name: {      $regex: “String seraching”,      ‘$options’: ‘i’      }   }}

b). Partial Text Search by multiple fields in collection :

If we want to search by more than one field (Multiple fields)in a particular collection then we can use that code in the aggregate query

{  $match: {    $or: [     { name: {       $regex: “String to be searched”,       ‘$options’: ‘i’     }},     { email: {       $regex: String to be searched,       ‘$options’: ‘i’     }}    ]}

},