首页 > 解决方案 > 本地字段和外部字段不起作用的查找管道内的项目

问题描述

我在下面编写了一些代码行,用于在查找中获取一些特定字段,例如

       $pipeline = array(
            array(
                '$match' => $query
            ),
            array(
                '$lookup' => array(
                    'from' => 'studentTbl',
                    'localField' => '_id',
                    'foreignField' => 'activity_details.activityId',
                     'pipeline' => [
                        ['$project' => [ '_id' =>  1.0, 'activity_details' => 1.0] ],
                     ],   
                    'as' => 'studentsOfActivities'
                )
            ),
           ....
           ....
        );

     return $this->db->activitiesTbl->aggregate($pipeline)->toArray();

基本上 studentTbl 有很多字段和嵌入的文档。在上面的代码中,我首先使用外部和本地字段通过查找来获取,然后确定哪些字段应该投射到管道中。

上面的代码不起作用......请帮助!

标签: mongodbmongodb-queryaggregation-frameworkmongodb-phpphp-mongodb

解决方案


您可以使用以下聚合

db.collection.aggregate([
  { "$match": $query },
  { "$lookup": {
    "from": "studentTbl",
    "let": { "activityId": "$_id" },
    "pipeline": [
      { "$match": { "$expr": { "$in": ["$$activityId", "$activity_details.activityId"] }}},
      { "$project": { "activity_details": 1 }}
    ],
    "as": "studentsOfActivities"
  }}
])

推荐阅读