PHP新MongoDB驱动程序中的全文搜索分数投影
我正在从旧的PHP MongoDB驱动程序升级代码: 要创建新的MongoDB驱动程序,请执行以下操作: 在以前的版本中,我有:PHP新MongoDB驱动程序中的全文搜索分数投影,php,mongodb,full-text-search,projection,Php,Mongodb,Full Text Search,Projection,我正在从旧的PHP MongoDB驱动程序升级代码: 要创建新的MongoDB驱动程序,请执行以下操作: 在以前的版本中,我有: $db->collection->find([ '$text' => [ '$search' => "stackoverflow" ] ], [ 'score' => [ '$meta' => 'textScore' ] ])->sort([ 'sort' => [ 'score' => [ '$m
$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' ] ]
]);
$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);
但我有一个错误:
对于所有$meta排序键,BadValue必须具有$meta投影
这是因为,分数投影不再发生了。如果只删除排序选项和日志结果,您将看到结果数组中没有分数。根本没有关于它的文档
有人知道如何解决这个问题吗
谢谢如果您想使用新的PHP驱动程序搜索Mongo文本索引并在textScore字段上排序,您必须使用Query类,在那里添加过滤器和选项,然后使用Manager类执行。在您的情况下,可能是这样的:
$db->collection->find([
'$text' => [ '$search' => 'stackoverflow' ]
],
[
'score' => [ '$meta' => 'textScore' ],
'sort' => [ 'score' => [ '$meta' => 'textScore' ] ]
]);
$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);
请参阅文档页面,了解第一个注释似乎非常有用。也可以这样做:
$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']
]
]
);