【发布时间】:2016-06-01 19:25:20
【问题描述】:
我用这个在桌子上敲打我的头太久了......
我有两个 MongoDB 集合:“聊天室”和“用户”。 "chatroom" 集合中的 "user_id" 键指向 "users" 集合中的特定单个用户。
我正在尝试使用 $lookup 聚合查询与用户一起获取聊天室,我目前拥有的是这个:
$this->mongo->chatroom->aggregate(
array('$lookup' => array(
'from' => 'users',
'localField' => 'user_id',
'foreignField' => '_id',
'as' => 'user'
))
);
但是,这会在集合中返回一个空的“用户”字段。奇怪的是,如果我尝试用设置为 _id.$id 值的自定义“uid”替换“_id”,它会按预期工作:
$this->mongo->chatroom->aggregate(
array('$lookup' => array(
'from' => 'users',
'localField' => 'user_id',
'foreignField' => 'uid', // uid = _id.$id
'as' => 'user'
))
);
我发现问题是“_id”是 ObjectId 而“user_id”是字符串。但是我不知道如何很好地处理这个问题......
【问题讨论】: