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 ] ] 
        ]
    )
    
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?