【问题标题】:Sort documents based on array field size根据数组字段大小对文档进行排序
【发布时间】:2016-07-12 14:32:36
【问题描述】:

我正在尝试使用一个名为“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 个 emp)
  2. 名字2 (2)
  3. 名字1 (1)

【问题讨论】:

    标签: php mongodb aggregation-framework


    【解决方案1】:

    我们需要$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 ] ] 
        ]
    )
    

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多