dozabg1616 2018-04-07 19:52
浏览 1390
已采纳

将mongoDB $ lookup与$ project结合使用

Right now I'm using the $project aggregation for filtering out unnecessary fields. Also I'm using the $lookup aggregation to link two collections togethe and I know how to use both of them in the main collection. Now my question is; how can I put this $project aggregation inside of a lookup? What I have now is looks like this:

[
            '$lookup' => [
                'from' => Media::collectionName(),
                'localField' => '_id',
                'foreignField' => 'project_id',
                'as' => 'mediaList'
            ]
        ],
        [
            '$project' => [
                'title' => 1,
                'owner_id' => 1,
                'owner_name' => 1,
                'created_at' => 1,
                'updated_at' => 1,
                'status' => 1,
                'discount' => 1,
                'company' => 1,
                'media' => [
                    '$filter' => [
                        'input' => '$mediaList',
                        'as' => 'media',
                        'cond' => $mediaFilter
                    ]
                ]
            ]
        ],

So I can filtering out the unnecessary fields in the main collection. How can I do this in the sub-collection?

  • 写回答

1条回答 默认 最新

  • duanjiu2701 2018-04-11 12:15
    关注

    If I understood your question correctly, you want to apply a $filter operation on your $mediaList field.

    To avoid a redundant $project stage (where you have to declare every single field you want to keep), use $addFields stage instead, like this :

        [
            '$lookup' => [
                'from' => Media::collectionName(),
                'localField' => '_id',
                'foreignField' => 'project_id',
                'as' => 'media' // Note that I use the same name for the field
            ]
        ],
        [
            '$addFields' => [
                'media' => [
                    '$filter' => [
                        'input' => '$media',
                        'as' => 'media',
                        'cond' => $mediaFilter
                    ]
                ]
            ]
        ],
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?