更改汇总结果

时间:2019-03-17 16:39:36

标签: javascript mongodb mongoose

我目前有一个几乎可以正常工作的聚合查询,它将获取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 }
]}

1 个答案:

答案 0 :(得分:1)

您需要再使用一个$group阶段,以便在$unwind

之后将拆分后的数组重塑为原始形式
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" },
  }}
])