如何在php中转换mongo db查询

时间:2017-01-24 09:07:48

标签: php arrays json mongodb

我们已经创建了MongoDB查询,但它没有转换为PHP

MongoDB查询

db.crawled_jobs.aggregate(
 [ 
   {   
       $geoNear: { 
           near: {  
              type: "Point", 
              coordinates: [-73.86, 41.07 ] 
           }, 
           distanceField:"dist.calculated", 
           maxDistance: 100000, 
           includeLocs: "dist.location", 
           num: 1225, 
           spherical: true,
           "query": { "title": /sales/ } 
       } 
   }
])

Mongodb查询工作正常,我们得到结果

在php \MongoDB\Driver\Command

在PHP中创建一个数组并用于MongoDB查询

$queryString = [['$geoNear'=> ['near'=> [ 'type'=> "Point",'coordinates'=> [$lon,$lat] ], 'distanceField'=> "dist.calculated",'maxDistance'=> $maxDistance, 'includeLocs'=> "dist.location", 'num'=> 10000, 'spherical'=> true, 'query' => ['title' => '/sales/'] ] ] ];

在此查询之后,MongoDB查询看起来像这样

db.crawled_jobs.aggregate([{"$geoNear":"near":"type":"Point","coordinates":[-73.86,41.07]},"distanceField":"dist.calculated","maxDistance":100000,"includeLocs":"dist.location","num":1225,"spherical":true,"query":{"title":"\/sales\/"}}}])

我们没有得到结果,因为它在查询中添加了反斜杠  "query":{"title":"\/sales\/"} But we need like this "query": { "title": /sales/ }

任何人都可以帮助我们

\MongoDB\Driver\Command不接受字符串:(它需要唯一的数组不是字符串)

2 个答案:

答案 0 :(得分:2)

用这个

修复它
'query' => ['title'=> array('$regex' => 'NYC')]

答案 1 :(得分:0)

您需要使用MongoDB\BSON\Regex类生成正则表达式,如下所示:

'query' => ['title' => new MongoDB\BSON\Regex('sales')]