Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First Name and Last Name Combine search in mongoDB

I have store two field FirstName and LastName stored in MongoDB.from Frontend, I am receiving a string containing both first name and last name separated by space I need a find query which searches both first name & last name combined.

here is eg. scenario

in DB I have following object

{ firstName: "Hemant Kumar", lastName: "Rajpoot" };

if i receive "Hemant Kumar Rajpoot" it should match.If possible please don't give solution with aggregeation.

like image 788
Hemant Rajpoot Avatar asked Sep 18 '19 07:09

Hemant Rajpoot


People also ask

How do I find first name and last name in MongoDB?

You can do it with combination of $expr, $eq and $concat. Show activity on this post. Show activity on this post. It's as simple as checking if the fields entered ( firstname , lastname ) matches any user in the database.

Can we join two collections in MongoDB?

Hi, Yes, you can join 2 collections with Aggregation Framework and $unionWith stage. Here are the docs with syntax and examples, so you can check how to do it.

What is GTE and LT in MongoDB?

Comparison Operators Matches if values are greater than the given value. $lt. Matches if values are less than the given value. $gte. Matches if values are greater or equal to the given value.

Can we use $match in Find MongoDB?

Now let's see what the restrictions for matches in Mongodb are as follows. You can't utilize $where in $match questions as a feature of the collection pipeline. Use the $geoNear stage rather than the $match stage. Use $geoWithin inquiry administrator with $center or $centerSphere in the $match stage.


2 Answers

You can use $regexMatch if you are using latest mongodb version 4.2

db.collection.find({
  "$expr": {
    "$regexMatch": {
      "input": { "$concat": ["$first", " ", "$last"] },
      "regex": "a",  //Your text search here
      "options": "i"
    }
  }
})

MongoPlayground

like image 75
Ashh Avatar answered Oct 07 '22 17:10

Ashh


You can do it with combination of $expr, $eq and $concat.

Example:

db.yourCollection.find({
  $expr: {
    $eq: [
      {$concat: ["$firstName", " ", "$lastName"]}, 
      "Hemant Kumar Rajpoot" // your full name to search here
    ]
  }
})
like image 3
Cuong Le Ngoc Avatar answered Oct 07 '22 17:10

Cuong Le Ngoc