4

I want to find all documents containing the word "school" in ANY of their subdocuments fields, for example, if we have two documents:

{
    name: "aa",
    schools: [
        {
            name: "high school",
            description: "aaaa"
        },
        {
            name: "a1",
            description: "blabla bla school"
        },
        ...
    ],
},
{
    name: "bb",
    schools: [
        {
            name: "bbb",
            description: "First school of ..."
        },
        {
            name: "b school",
            description: "bbb  bb b",
            ...
        }
    ],
},

These documents should match with the name or/and description of the first or/and second school.

I tried this query without success:

{
    schools: /.*school.*/
}

And this too, by listing fields:

{
    school: [
        { name: /.*school.*/ },
        { description: /.*school.*/ },
        ...
    ]
}

Is their a way to perform this?

2 Answers 2

4

If you need a true wildcard query, then @a-h's answer regarding a text index is the way to go. But you can also do this with an $or query that checks multiple fields for matches:

db.schools.find({
  $or: [
    { 'schools.name': /school/ },
    { 'schools.description': /school/ },
    ...
  ]
})
Sign up to request clarification or add additional context in comments.

Comments

3

The easiest way is to create a full-text index.

You can do this by following the documentation at https://docs.mongodb.org/manual/core/index-text/

The index can then be queried with the $text operator: https://docs.mongodb.org/manual/reference/operator/query/text/

Create Index on All Fields

db.schools.createIndex( { "$**": "text" } )

Search

db.schools.find({
  $text:
    {
      $search: "school",
      $language: "en",
      $caseSensitive: false,
      $diacriticSensitive: false
    }
})

1 Comment

This response works too, but a wildcard index on all string data in my collection would be too big I think or not usefull. Thanks anyway!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.