我正在从旧的PHP MongoDB驱动程序升级我的代码:http://php.net/manual/en/class.mongoclient.php
到新的MongoDB驱动程序:http://php.net/manual/en/set.mongodb.php
在以前的版本中,我有这样的:
$db->collection->find([
'$text' => [ '$search' => "stackoverflow" ]
],
[
'score' => [ '$meta' => 'textScore' ]
])->sort([ 'sort' => [ 'score' => [ '$meta' => 'textScore' ] ] ]);
在新版本中,游标上不再有排序函数,您必须将其作为一个选项传递。新代码是这样的:
$db->collection->find([
'$text' => [ '$search' => 'stackoverflow' ]
],
[
'score' => [ '$meta' => 'textScore' ],
'sort' => [ 'score' => [ '$meta' => 'textScore' ] ]
]);
但是我得到一个错误:"BadValue必须对所有$meta排序键有$meta投影"
这是因为,分数投射不再发生了。如果您只是删除排序选项并记录结果,您将看到,结果数组中没有分数。没有关于它的任何文档。
有人知道如何解决这个问题吗?
谢谢
如果想用新的PHP驱动程序搜索Mongo文本索引并在textScore字段上排序,则必须使用Query类,在那里添加过滤器和选项,然后使用Manager类执行。在你的例子中,它应该是这样的:
$filter = [
'$text' => ['$search' => 'stackoverflow']];
$options = [
'projection' => [
'score' => ['$meta' => 'textScore']
],
'sort' => [
'score' => ['$meta' => 'textScore']
]
];
$mng = new MongoDB'Driver'Manager("mongodb://yourdbserver:27017");
$mongoQuery = new MongoDB'Driver'Query($filter, $options);
$cursor = $mng->executeQuery('db_name.collection_name', $mongoQuery);
请参阅Query类的文档页面,第一个注释似乎非常有用。
也可以这样做:
$collection = (new MongoDB'Client)->DB->COLLECTION;
$cursor = $collection->find(
['$text' => ['$search' => 'stackoverflow']],
[
'projection' => [
'score' => ['$meta' => 'textScore']
],
'sort' => [
'score' => ['$meta' => 'textScore']
]
]
);
并带跳跃和限位:
$collection = (new MongoDB'Client)->DB->COLLECTION;
$cursor = $collection->find(
['$text' => ['$search' => 'stackoverflow']],
['skip' => 0,
'limit' => 20,
'projection' => [
'score' => ['$meta' => 'textScore']
],
'sort' => [
'score' => ['$meta' => 'textScore']
]
]
);