douzhechi2435 2016-06-27 13:49
浏览 131

根据数组字段大小对文档进行排序

I'm trying to use the size of an array called "empofthemonth" to sort each field returned by their amount of employee of the month wins.

Here is the insert code:

$db->users->insert(
    ["firstname" => "firstname1", 
     "lastname" => "test", 
     "email" => "test@email.org.uk", 
     "keyinfo" => 
        ["age" => 22,
         "gender" => "Male",
         "yearsemployed" => 1,
         "empofthemonth" => ["Apr"]]
     ]);

$db->users->insert(
    ["firstname" => "firstname2", 
     "lastname" => "test2", 
     "email" => "test@email.co.uk", 
     "keyinfo" => 
        ["age" => 24,
         "gender" => "Female",
         "yearsemployed" => 5,
         "empofthemonth" => ["Feb", "Mar"]]
     ]);

$db->users->insert(
    ["firstname" => "firstname3", 
     "lastname" => "test2", 
     "email" => "test@email.com", 
     "keyinfo" => 
        ["age" => 31,
         "gender" => "Female",
         "yearsemployed" => 2,
         "empofthemonth" => ["Jan", "May", "Jun"]]
     ]);

I realise that aggregation might be used but i cannot work out the full syntax.

To conclude the query results should be in this order:

  1. firstname3 (3 emp of the months)
  2. firstname2 (2)
  3. firstname1 (1)
  • 写回答

1条回答 默认 最新

  • duanjiu2701 2016-06-27 14:14
    关注

    We need to $project our documents and return the $size then $sort each document by that "size" in descending order. Note that to access the array field, we need to use the "dot notation".

    db.users.aggregate(
        [
            { "$project": { 
                "firstname": 1, 
                "lastname": 1, 
                "email": 1, 
                "keyinfo": 1, 
                "sz": { "$size": "$keyinfo.empofthemonth" } 
            }}, 
            { "$sort": { "sz": -1 } } 
        ]
    )
    


    Everything in PHP:

    $db->users->aggregate(
        [
            [ "$project" => [ 
                "firstname" => 1, 
                "lastname" => 1, 
                "email" => 1, 
                "keyinfo" => 1, 
                "sz" => [ "$size" => "$keyinfo.empofthemonth" ]
            ]], 
            [ "$sort" => [ "sz" => -1 ] ] 
        ]
    )
    
    评论

报告相同问题?

悬赏问题

  • ¥15 聚类分析或者python进行数据分析
  • ¥15 如何用visual studio code实现html页面
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?