Full-text search and sort php mongodb

i nead to do a full text index search, and this code works:

$cursor=$collection->find(array('$text'=>(array('$search'=>$s))),
                    array("score"=> array('$meta'=>"textScore"))
        );

I am trying to sort the cursor with:

$cursor =$cursor->sort(array("score"=>1));

when i try to read

var_dump($cursor->getNext());

I gave me this error Uncaught exception "MongoCursorException" with the message "localhost: 27017: Canonicalize query: BadValue cannot have non-meta sorting without metadata in the meta projection"

any idea?

+4
source share
1 answer

You are trying to sort a meta field, not a regular field name.

The second argument $collection->find()determines which fields of the document that you (do / do not) want to return to the request.

SELECT *... vs SELECT field1, field2 ... SQL.

, MongoDB 2.6 , , $meta. "" ( ). - "" , .

$text , .. , , . - , .

, $text, "textScore". , , :

array("myFieldname" => array('$meta' => 'keyword'))

, (textScore) "score" , $collection->find():

array("score" => array('$meta' => 'textScore'))

, "", , "textScore" $.

, , .

, $meta projection

array('score' => array('$meta' => 'textScore'))

:

<?php
$mc = new MongoClient();


$collection = $mc->selectCollection("myDatabase", "myCollection");

$string = "search string";
$cursor = $collection->find(
    array('$text' => array('$search' => $string)),
    array('score' => array('$meta' => 'textScore'))
);

$cursor = $cursor->sort(
    array('score' => array('$meta' => 'textScore'))
);

foreach($cursor as $document) {
    var_dump($document);
}
+5

Source: https://habr.com/ru/post/1536596/


All Articles