3

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.

Mukesh Joshi
  • 2,784
  • 4
  • 24
  • 34

1 Answers1

3

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(); 
Cptmaxon
  • 505
  • 2
  • 12
  • 1
    Is there a way to search if $country would be a array. Means something like this. $country => Array ( [0] => Abkhazia [1] => Afghanistan ) – Mukesh Joshi Dec 09 '15 at 06:44
  • sure if you look at the API at [jenssegers API](https://github.com/jenssegers/laravel-mongodb) under WhereIn you'll see the correct formatting `$countries = ['US','SPAIN']; $results = Products::whereIn('product_data.6',$countries)->get();` – Cptmaxon Dec 09 '15 at 07:00