0

My mongodb table has a field which has object value like

_id : ObjectId("59ad227e191cc3a4c33ade07")
user_info : {"first_name": "Shraddha", "last_name": "Banerjee", "Zip": "90242", "City": "SantaBarbara"}

I want to find the users with Zip: 90242.

I tried doing it like:

$users = User::where('user_info.Zip','=', 90242)->get();

But this gives me empty result. How can this be achieved ?

  • First take `$info = $user_info['Zip'];` and then use `$users = User::where($info,'=', 90242)->get();` Let me know if this works! – Hiren Gohel Sep 04 '17 at 11:51
  • Have you tried it?? – Hiren Gohel Sep 05 '17 at 07:16
  • Hi @Hiren, It doesn't work. Its an object stored inside user_info. It gives error : Undefined variable: user_info. Well i also tried using $info = "user_info.Zip"; $users = User::where($info,'=', 90242)->get(); – Shraddha Banerjee Sep 06 '17 at 08:51
  • `$user_info` i said, you need to take your variable where json object comes from! – Hiren Gohel Sep 06 '17 at 08:55
  • I just have the Zip coming from my POST request. This JSON is the stored document in my mongoDB collection. This I have achieved doing in MySQL like this : $users = User::where('user_info->Zip', $zip) ->where('user_info->DateOfBirth', 'like', '%'.$date_of_year.'%') ->get(['user_info', 'user_id']); But using mongo cannot fetch it.. – Shraddha Banerjee Sep 06 '17 at 09:07

2 Answers2

1

try this instead,

$users = User::where('user_info.Zip', '90242')->get();
Vipin
  • 96
  • 6
0

it seems that your zip data is stored string and when you query it you are using integer.

$users = User::where('user_info.Zip','=', '90242')->get();

try to cast zip to string when you do the query

ariawan
  • 198
  • 1
  • 8