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

时间:2016-06-27 13:49:58

标签: php mongodb aggregation-framework

我试图使用名为" empofthemonth"的数组的大小。对按月赢得的员工数量返回的每个字段进行排序。

这是插入代码:

$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"]]
     ]);

我意识到可能会使用aggregation,但我无法弄清楚完整的语法。

总结查询结果应该按以下顺序排列:

  1. firstname3(月份3个月)
  2. firstname2(2)
  3. firstname1(1)

1 个答案:

答案 0 :(得分:0)

我们需要$project我们的文档,并按照“尺寸”按降序返回每个文档的$size然后$sort。请注意,要访问数组字段,我们需要使用"dot notation".

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

PHP中的所有内容:

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