我试图使用一个名为" empothemonth "的数组的大小来按每月获胜的员工数量对每个字段进行排序。
插入代码:
$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"]]
]);
我意识到聚合可能被使用,但我不能算出完整的语法。
查询结果应该是这样的顺序:
- firstname3(每月3次)
- firstname2 (2)
- firstname1 (1)
我们需要$project
我们的文档,并返回$size
然后$sort
每个文档按"大小"降序。注意,要访问数组字段,我们需要使用"点表示法"。
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 ] ]
]
)