我目前有一个几乎可以正常工作的聚合查询,它将获取users
数组,并按其score
对对象进行排序。
但是由于某些原因,没有获得预期的输出,整个family
数据将再次打印出来。
我该如何解决?
执行的代码:
return Family.aggregate([
// Initial document match (uses index, if a suitable one is available)
{ $match: {name: 'Management'}},
// Expand the scores array into a stream of documents
{ $unwind: '$users' },
// Sort in descending order
{ $sort: {
'users.score': -1
}}]
当前结果:
{ _id: 5c8e5c79e55ef42ce4923e0b,
name: 'Management',
time_started: 1552833657354,
location: 1,
isFamily: true,
last_member: 0,
score: 0,
users:
{ userid: '5c852292d1bd911abc4957dc',
joined_date: 1552839246371,
permission: 5,
upgrade: 0,
score: 141,
_id: 5c8e724e6e5e6512447c1a61 },
__v: 0 },
{ _id: 5c8e5c79e55ef42ce4923e0b,
name: 'Management',
time_started: 1552833657354,
location: 1,
isFamily: true,
last_member: 0,
score: 0,
users:
{ userid: '5c8522a96bcca9268c0753fe',
joined_date: 1552833657354,
permission: 6,
upgrade: 0,
score: 32,
_id: 5c8e5c79e55ef42ce4923e0c },
__v: 0 } ]
想要的结果:
{
name: 'Management',
time_started: 1552833657354,
location: 1,
isFamily: true,
last_member: 0,
score: 0,
users:
[{ userid: '5c852292d1bd911abc4957dc',
joined_date: 1552839246371,
permission: 5,
upgrade: 0,
score: 141,
_id: 5c8e724e6e5e6512447c1a61 },
__v: 0 },
{ userid: '5c8522a96bcca9268c0753fe',
joined_date: 1552833657354,
permission: 6,
upgrade: 0,
score: 32,
_id: 5c8e5c79e55ef42ce4923e0c },
__v: 0 }
]}
答案 0 :(得分:1)
Family.aggregate([
{ "$match": { "name": "Management" }},
{ "$unwind": "$users" },
{ "$sort": { "users.score": -1 }},
{ "$group": {
"_id": "$_id",
"users": { "$push": "$users" },
"name": { "$first": "$name" },
"time_started": { "$first": "$time_started" },
"isFamily": { "$first": "$isFamily" },
"last_member": { "$first": "$last_member" },
"score": { "$first": "$score" },
}}
])