【问题标题】:Project inside pipeline of lookup with local field and foriegn field not working本地字段和外部字段不起作用的查找管道内的项目
【发布时间】:2018-12-19 19:18:08
【问题描述】:

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

       $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 有很多字段和嵌入的文档。在上面的代码中,我首先使用外部和本地字段通过查找来获取,然后确定应该将哪些字段投影到管道中。

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

【问题讨论】:

  • activity_details 是数组还是对象?
  • 它在一个数组中(studentTbl的嵌入文档)

标签: mongodb mongodb-query aggregation-framework mongodb-php php-mongodb


【解决方案1】:

你可以使用下面的聚合

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"
  }}
])

【讨论】:

    【解决方案2】:

    如果你们正在寻找类似以下的查询,那么这里是答案: 在MongoDB中使用带有本地字段和外部字段内部聚合方法的项目。

    db.collection.aggregate([
                    {
                        $lookup: {
                            from: "users", // collection name in db
                            localField: "user_id",
                            foreignField: "_id",                           
                            as: "userdata",                            
                        },
    
                    },
                    {$match :{_id: {$in:losers} }},
                    {$project:
                        {
                          "answer":1,"_id":1,"win_status":1,"user_id":1,"user_id":1,
                            "userdata":{"name":1,"image":1,"email":1},
                        }
                    }
                ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 2015-07-20
      • 2015-06-18
      • 1970-01-01
      • 2021-08-22
      相关资源
      最近更新 更多