Reputation: 2991
I am using a jenssegers/laravel-mongodb library in a project. I have a collection in which a subdocument is created with other details. Now I have to implement a search query to search in the sub-document of the collection. The subdocument is product_data in which I want to search in index 6 of it. I want to search the country name in it. How can I do this.The structure of collection is as follows:
{
"_id": ObjectId("564d32f191c1cb1f087d7c71"),
"userid": "55c487a1083f11aa1b8b4567",
"shopid": "anotherstore",
"postedby": null,
"purpose": "sell",
"cat_ids": [
"TDC00-001-001",
],
"postdate": "2015-11-19",
"desc": "T-SHIRT",
"thumb": "http://test.local/uploads/product_img/prod-8yKsMHC2-1447895652.jpg",
"product_data"▼: {
"1": "2015-11-19",
"2": "anotherstore",
"3": "T-SHIRT",
"4": "1245",
"6": "Styling features include twin needle stitching for neatness and strength on the collar, sleeve and h",
"5": "US",
"6": "US"
}
}
I have tried with some queries searching but got no success. Those are:
$country=Array(
[0] => Australia
)
$country = Products::whereIn('product_data[6]', $country)->get();
or
$country = Products::where('books', 'elemMatch', array([6] => $country))->get();
If someone know please help.
Upvotes: 3
Views: 1593
Reputation: 525
since the query for sub-documents looks like this in mongo:
db.products.find({'product_data.6':'US'});
you just need to recreate that structure in your code :
$country = 'US';
$queryFilter = ['product_data.6'=>$country];
Products::where($queryFilter)->first(); //or get whatever.
if you want to search in an array of countries you'll have to use whereIn method
$countries = ['US','SPAIN'];
$results = Products::whereIn('product_data.6',$countries)->get();
Upvotes: 3