Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for users by both first and last name with MongoDB?

I have a basic collection of users that have their firstName, lastName and a few other details.

How would I simply search for users by a combination of both names, or partial search?

For example, for a collection of:

{
   firstName: Bob,
   lastName: Jerry
}, {
   firstName: Clark,
   lastName: Mcbobby
}

If the search term was bob, both users would be returned since the first documents firstName is bob, and the last users lastName contains bob. If bob j was the search term, just the first document would be returned since if both names are combine, it equals Bob Jerry which matches the search term.

I tried creating a basic aggregate to concatenate the names and then make a match, although Mongoose kept throwing me an error of: Arguments must be aggregate pipeline operators.

Here is my current code:

User.aggregate({
    $project: { "name" : { $concat : [ "$firstName", " ", "$lastName" ] } },
    $match: {"name": {$regex: "/bob j/i"}}
}).exec(function(err, results) {
    ...
});
like image 463
Fizzix Avatar asked May 30 '16 12:05

Fizzix


People also ask

How do I use wildcard search in MongoDB?

Create a Wildcard Index on All Fields With this wildcard index, MongoDB indexes all fields for each document in the collection. If a given field is a nested document or array, the wildcard index recurses into the document/array and stores the value for all fields in the document/array.

How do I search multiple documents in MongoDB?

You can query for multiple documents in a collection with collection. find() . The find() method uses a query document that you provide to match the subset of the documents in the collection that match the query.

How do I search for a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

Which of the following is used to check greater than or equal to in MongoDB?

$gte selects the documents where the value of the field is greater than or equal to (i.e. >= ) a specified value (e.g. value .)


1 Answers

I see couple of mistakes in your code causing undesired result.

  1. Aggregation pipeline accepts array of aggregation framework operations. In your case, you are missing [] operator. It should be like

    User.aggregate([{$project...},{$match...}])

  2. In $match stage you are using regex, if you are using /../ style of regex, you don't need to wrap it around string quotes. It should be /bob j/i

Here is finished example:

User.aggregate([
  {$project: { "name" : { $concat : [ "$firstName", " ", "$lastName" ] } }},
  {$match: {"name": {$regex: /bob j/i}}}
]).exec(function(err, result){
  console.log(result);
});

You should see [ { _id: 574c3e20be214bd4078a9149, name: 'Bob Jerry' } ] on screen.

like image 176
Saleem Avatar answered Sep 28 '22 03:09

Saleem