0

i want to search in the whole users model values, if admin searches for example a number or a string if the there is a documnet with that value (or that value includes the admin input) in the users model values, mongoose should return all found documents.

how can i implement such thing?

something like this :

const adminInput = req.query.searchText
const foundDocument = await users.find({ '*': includes(adminInput) }) // very simple xD
res.send(foundDocument)
mahdi
  • 207
  • 1
  • 15

1 Answers1

0

As @NeNad points out, this question has been asked and answered many times. Another example is this question.

I'm just chiming in about two things in particular about the phrasing of this question that caught my attention. The first is:

if admin searches for example a number or a string if the there is a documnet with that value (or that value includes the admin input)

This type of searching can only be applied to string values. There is no concept of 3 being "in" the value of 537. There is, however, the concept of the character "3" being inside of the string "537".

The second thing somewhat overlaps with that and the includes(adminInput) from the code. The direct $text searching functionality provided in the database does not handle partial matches. You would likely need to look into alternatives such as Atlas Search or coupling Elasticsearch beside your MongoDB cluster to get the full functionality you are describing.

user20042973
  • 4,096
  • 2
  • 3
  • 14
  • 1
    i also want to search in number fields, any help? for the second one i guess i can use regexp to do that. – mahdi Oct 21 '22 at 18:42
  • Looks like there is an article about how to use Atlas Search to query numbers [here](https://www.mongodb.com/docs/atlas/atlas-search/tutorial/query-date-number-fields/). Regex itself can only be applied against a string (though that string can contain numeric characters). – user20042973 Oct 21 '22 at 18:52
  • 1
    well, does this atlas search solution work on local server mongodb database implementation or this only will work on atlas mongodb database? – mahdi Oct 21 '22 at 19:04
  • Only in Atlas. So your general options seem to be 1) Move to Atlas to leverage Atlas Search 2) Build a custom query that enumerates all of the possible field names in a large `$or` that contains a regex match for each of them 3) Leverage `$text` which lacks partial matching capabilities or 4) Stream your data to a search engine like Elasticsearch/Lucene. – user20042973 Oct 21 '22 at 19:16
  • 1
    for 1 & 4 it will cost much, for 2 & 3 i wont find numbers (in numbers) but at least i found users.find({ : new RegExp() }) a better way, it has partial matching but im not sure about its performance. – mahdi Oct 22 '22 at 09:39
  • the 2nd option is the best! 2) Build a custom query that enumerates all of the possible field names in a large $or that contains a regex match for each of them – mahdi Oct 22 '22 at 18:08