我目前正在研究Laravel。我的MongoDB中有两个集合,集合'users'具有用户详细信息,集合'user_details'具有与其他活动相关的其他一些用户详细信息。这两个集合都有一个共同的字段“ user_id”。我想进行汇总查询,以便可以通过单个查询获取结果。
最初,我要查询50个用户,然后循环访问用户集合中的“ user_id”字段,以从“ user_details”集合中获取用户详细信息(如果有)。由于某些原因,它不适用于某些用户。
//intially i was trying this
function get_mongo_user_details($skip,$limit){
$users = DB::connection('mongodb')->collection('users')-
>skip($skip)->take($limit)->get()->toArray();
$count = 0;
foreach ($users as $user) {
$subs = DB::connection('mongodb')-
>collection('user_details')-
>where('user_id',$user['user_id'])->get()-
>toArray();
if (!empty($subs)) {
$users[$count]['details'] = $subs;
}
$count++;
}
return $users;
}
//later I tried an aggregate query
$users = DB::connection('mongodb')->collection('users')->raw()-
>aggregate([
[
'$lookup' =>
[
'from' => 'user_details',
'localField' => 'user_id',
'foreignField'=> 'user_id',
'as'=> 'details'
]
]
])->skip($skip)->take($limit)->get()->toArray();
//I actually don't have that much of knowledge about mongoDB aggregate query. I read mongoDB docs but wasn't that helpful for me.
预期结果是来自“用户”集合的数组,其键为“细节”和“ user_details”集合值。但是我收到错误或带有空白集合值的MongoDB对象。