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 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?