Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

227
Visualizações
PHP Mongo: Search for a particular text in whole collection

I want to get all documents that have a specific word either in any nested json. A document in collection looks like this;

Man:{
        First name: 'F-Name'
        Last name: 'L-Name'
        hobbies:{
            sports:'cricket'
            watching: 'films'
        }
        Likeness:{
            name: 'F-name'
            fruit: 'chikoo'
        }
    }

and there are multiple such documents in collection. For example I want to find all the documents that have word F-name. See in the above json. F-name is in 2 nested jsons. But it can be in only one or multiple. What is speedy and intelligent way for finding all that documents rather than giving any field or nested Json name (First name, Likeness->name in above case). Is there any way?

$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$filter = [ ?? ];
$query = new MongoDB\Driver\Query($filter);     
$res = $mng->executeQuery("Database.myName", $query);

Edit 1 On the suggestion of @Shail Paras I run the following code;

<?php
    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    $query = new \MongoDB\Driver\Query(['createIndex' => ['*' => 'text']]);
    $res = $mng->executeQuery("BBC_Database.BBC", $query);
    $filter = ['$text' => ['$search' => "\"F-name\""]];
    $query1 = new MongoDB\Driver\Query($filter);     
    $cursor = $mng->executeQuery("Database.Col", $query1);
    $filteredData = iterator_to_array($cursor);
    echo "<pre>";
    print_r($filteredData);
?>

But it gives;

Fatal error: Uncaught exception 'MongoDB\Driver\Exception\RuntimeException' with message 'text index required for $text query' in C:\wamp64\www-------filename.php on line 7

What is text index according to the error?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Ok.. That is the error of Text Search because text search only works if indexing is created, and i think your indexing part is not working. that's why it is throwing that exception. and I'm sorry for being in hurry. but Here is your solution:

Step 1 : Create Indexes in All Documents using Command

$manager = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
$command = new MongoDB\Driver\Command([
    "createIndexes" => "Col",
    "indexes"       => [[
        "name" => "indexName",
        "key"  => ["$**" => "text"],
        "ns"   => "Database.Col",
    ]],
]);
$result = $manager->executeCommand("Database", $command);
var_dump($result->toArray()); // this will show u indexing result

Step 2 : Run Your query

$filter = ['$text' => ['$search' => "\"F-name\""]];
$query1 = new MongoDB\Driver\Query($filter);     
$cursor = $manager->executeQuery("Database.Col", $query1);
$filteredData = iterator_to_array($cursor);
echo "<pre>";
print_r($filteredData);

Hope this can help you and if it did, then don't forget to read these articles:

Text Search & Text Indexes

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda