Reputation: 2422
How do I make mongodb text search work in Laravel? Please suggest.
I can do that on terminal -
db.coupons.find( { $text: { $search: "Search me here" } } )
But not sure how to do it in laravel.
Upvotes: 3
Views: 4473
Reputation: 5442
To search using laravel mongodb (with jenssegers/laravel-mongodb) you need to create an index first. Ex: db.articles.createIndex( { "subject" : "text" } )
, where subject
is the text attribute to make the search.
Then you can try a query in mongodb: db.articles.find( { $text: { $search: "coffee" } } )
or do it in Laravel:
$word = "coffee";
$response = Article::whereRaw(array('$text'=>array('$search'=> $word)))->get();
If you want to search by a phrase you need tu use the quotes. In mongodb: db.articles.find( { $text: { $search: "\"coffee shop\"" } } )
and Laravel:
$word = "coffee shop";
$response = Article::whereRaw(array('$text'=>array('$search'=> "\"" . $word . "\"")))->get();
Upvotes: 7
Reputation: 641
Since you are using https://github.com/jenssegers/laravel-mongodb, according to your code you can do say
$coupons= Coupons::where('$text' =>['$search' =>'Search me here' ]);
}))->get();
Upvotes: 1
Reputation: 7504
Add jenssegers/laravel-mongodb package in your composer.json and install that through composer update
. Visit added link, there you will get good source to deal with mongodb-laravel connection.
Have you tried something like:
$users = User::with(array('posts' => function($query)
{
$query->where('title', 'like', '%first%');
}))->get();
See if that helps.
Upvotes: 2