MongoDB - contains (LIKE) request in concatenated field

I am new to MongoDB.

I am programming an application with spring and mongodb data, and I have one class with two fields: firstname and lastname .

I need one query for documents containing one line in the full name ( firstname + lastname ).

For example: firstname = "Hansen David" , lastname = "Gonzalez Sastoque" and I have a query to find David Gonzalez . In this example, I expect there will be a match.

Combining two lines solves, but I do not know how to accomplish this.

+4
source share
3 answers

Create a new field in the array (call its names ) in the document, and in this array, each name will be separated by a space. In your example, the array will have the following contents:

  • hansen
  • David
  • Gonzalez
  • sastoque

(do everything in lower case to prevent case insensitive problems)

Before you execute your query, convert your input to lowercase and separate it with spaces as well.

Now you can use $ all operator to achieve your goal:

 db.persons.find( { names: { $all: [ "david", "gonzalez" ] } } ); 
+5
source

You can use the $where modifier in your queries:

 db.users.findOne({$where: %JavaScript to match the document%}) 

In your case, it might look like this:

 db.users.findOne({$where: "this.firstname + ' ' + this.lastname == 'Gonzalez Sastoque'"}) 

or that:

 db.users.findOne({$where: "this.firstname.match(/Gonzalez/) && this.lastname.match(/Sastoque/)"}) 

My last example does exactly what you want.

Update: Try the following code:

 db.users.findOne({$where: "(this.firstname + ' ' + this.lastname).match('David Gonzalez'.replace(' ', '( .*)? '))"}) 
+2
source

You must split your full name into first and last name, and then execute your query in both fields using the appropriate MongoDB query selector.

0
source

Source: https://habr.com/ru/post/1434706/


All Articles