Search for a keyword through all the fields in a collection

Hello,

MongoDB newbie here. I have a collection with multiple documents in it. All documents have similar fields.
I want to implement a single search function to find any document if any of the fields in that document matches the keyword.

For example, if I have documents that have fields first_name, last_name, middle_name and I search for “John”, if any of the previously mentioned fields contain “John” (it can be Johnathan, Johnny, John, etc.) to return that document.

thanks!

1 Like

I think the easiest way would just have db.collection.find({$or: [{first_name: “John”}, {last_name: “John”}, {middle_name: “John”}, ]})

whoops misread your question! You can use a regex statement to see if the value in any field contains “john”:
db.collection.find({$or: [{first_name: /^John/ }, {last_name: /^John/ }, {middle_name: /^John/ } ]})

Hi @Beka_Modebadze - welcome to MongoDB and the Forums! One way to do this is via a $search stage in the aggregation pipeline using Atlas Search. Then: You have three query options in Atlas Search: autocomplete, regex, and wildcard.

Regex works best with the keyword analyzer, which is an exact match type. An example of what your query could be with regex is:

    {
      index: 'name_test',
      "regex": {
            "query": "John.*",
            "path": "first_name",
            "allowAnalyzedField": true,
        }
    }

Autocomplete requires that you define the field as type autocomplete. This is an example of an Autocomplete index:

{
  "mappings": {
    "dynamic": true,
    "fields": {
      "name": [
        {
          "foldDiacritics": true,
          "maxGrams": 10,
          "minGrams": 2,
          "tokenization": "nGram",
          "type": "autocomplete"
        }
      ]
    }
  }

With this query:

{
  index: 'autocompleteMinTwoDynamic',
  autocomplete: {
    query: 'Jo',
    path: 'first_name'
  }
}
2 Likes

Hello @Beka_Modebadze, welcome to the MongoDB Community forum!

You can also try Text Search using Text Indexes. You can specify the search index on specific fields, as part of a compound index or as a Wild Card Text Index. The Wild Card Text Index allows search all fields of the document.

Note that this is not the same as the Atlas Search.

Thanks for the suggestion @prasad_saya!

At MongoDB we do suggest using Atlas Search over $text where possible, since text indexes only work for text-based content and the $text operator can only be modified in limited ways. Furthermore, $text is much slower, more resource intensive, and less tunable.

Let me know if you have any other questions!