Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

226
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda