代码之家  ›  专栏  ›  技术社区  ›  cjmling

带前缀的MongoDB查询$lookup

  •  1
  • cjmling  · 技术社区  · 8 年前

    rounds 和 summaries

    记录 回合

    {
       "_id": "2018-04",
       "name": "Round 2018-04" 
    }
    

    记录 看起来像

    {
       "phase": "round:2018-04",
       "userId": NumberLong(66325),
    }
    

    我想问一下 摘要 查找 回合 连接基于 phase 属于 摘要 进入之内 _id 属于

    问题: 如果没有前缀 round: 同相。

    到目前为止这是我的代码。

    $cursor = $this->mongo->selectCollection('summaries')->aggregate([
                array('$match' => []),
                array(
                    '$lookup' => [
                        'from' => 'rounds',
                        'localField' => 'phase',
                        'foreignField' => '_id',
                        'as' => 'roundDetail'
                    ]
                ),
                array(
                    '$unwind' => '$roundDetail',
                ),
                array(
                    '$project' => [
                        'userId' => 1,
                        'roundDetail.name' => 1
                    ]
                )
            ]);
    

    MongoDB版本3.4.16

    1 回复  |  直到 8 年前
        1
  •  1
  •   Ashh    8 年前

    你可以用 substrBytes 从字符串中删除字符。

    $cursor = $this->mongo->selectCollection('summaries')->aggregate([
        array('$match' => []),
        array('$addFields' => [ 'phase' => [ '$substrBytes' => [ '$phase', 6, 7 ] ] ] ),
        array(
            '$lookup' => [
                'from' => 'rounds',
                'localField' => 'phase',
                'foreignField' => '_id',
                'as' => 'roundDetail'
            ]
        ),
        array(
            '$unwind' => '$roundDetail',
        ),
        array(
            '$project' => [
                'userId' => 1,
                'roundDetail.name' => 1
            ]
        )
    
    ])