Jaskaran singh Rajal
Jaskaran singh Rajal

Reputation: 2330

how to convert mongo db query in php

We have created MongoDB query but it's not converted into PHP

MongoDB query

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 query working fine and we get results

In php \MongoDB\Driver\Command

Create an array in PHP and use for MongoDB query

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

after this query, MongoDB query look like this

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\/"}}}])

We didn't get result because it add backslash in query "query":{"title":"\/sales\/"} But we need like this "query": { "title": /sales/ }

Can anyone help us

\MongoDB\Driver\Command does not accept string :( it require the only array not string)

Upvotes: 2

Views: 219

Answers (2)

Jaskaran singh Rajal
Jaskaran singh Rajal

Reputation: 2330

Fix it with this

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

Upvotes: 2

Alex Blex
Alex Blex

Reputation: 37048

You need to use MongoDB\BSON\Regex class to generate regex as following:

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

Upvotes: 1

Related Questions