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

将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
                    ]
                ]
            ]
        ],
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛