如何在Mongoose聚合$lookup中匹配指定用户名称或邮箱?
MongoDB聚合查询修改:添加$lookup关联筛选条件
要实现关联userdetails集合时仅保留data.name='abc'或data.email='xyz@mail.com'的记录,需要将原有的简单$lookup替换为带自定义pipeline的版本,在pipeline中同时处理关联匹配和筛选条件。修改后的完整代码如下:
$results = $this->mongo_db->aggregate( 'reviewRatings', [ ['$match' => $where], ['$sort' => ['_id' => -1]], ['$skip' => (int)$start], ['$limit' => $limit], ['$lookup' => [ 'from' => 'userdetails', 'let' => ['reviewUserId' => '$user_id'], 'pipeline' => [ [ '$match' => [ '$expr' => ['$eq' => ['$_id', '$$reviewUserId']], '$or' => [ ['data.name' => 'abc'], ['data.email' => 'xyz@mail.com'] ] ] ], [ '$project' => [ '_id' => 1, 'data' => 1 ] ] ], 'as' => 'combined' ]], ['$project' => [ '_id' => 1, 'app_id' => 1, 'user_id' => 1, 'rating' => 1, 'received_on' => 1, 'review_date' => 1, 'max_rating' => 1, 'location' => 1, 'connection_type' => 1, 'is_replied' => 1, 'recommendation_type' => 1, 'combined._id' => 1, 'combined.data' => 1 ]] ] ); return $results;
关键修改说明:
- 替换原
localField/foreignField的匹配逻辑为let+pipeline组合:用let将当前reviewRatings文档的user_id传递到关联查询的pipeline中 - 在pipeline的
$match阶段同时完成两个逻辑:- 通过
$expr匹配userdetails的_id与传递过来的user_id - 用
$or筛选出符合data.name='abc'或data.email='xyz@mail.com'的记录
- 通过
- 在pipeline中提前添加
$project,仅保留需要的字段,减少不必要的数据传输
内容的提问来源于stack exchange,提问作者dev dev
相关产品推荐
相关产品推荐

