You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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阶段同时完成两个逻辑:
    1. 通过$expr匹配userdetails的_id与传递过来的user_id
    2. 用$or筛选出符合data.name='abc'或data.email='xyz@mail.com'的记录
  • 在pipeline中提前添加$project,仅保留需要的字段,减少不必要的数据传输

内容的提问来源于stack exchange,提问作者dev dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 04:52:35