2016-10-04 23 views
1

我有兩個Mongoose模式/模型。一個爲Team的球員,另一個爲Players本身。Mongo - 從幾個參考對象數組中取值的總和

// Other less relevant stuff 
goalkeepers: [{ 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Player' 
}], 
defenders: [{ 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Player' 
}], 
midfielders: [{ 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Player' 
}], 
attackers: [{ 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Player' 
}], 
points: Number 

球員

// Other less relevant stuff 
points: Number 

的問題是,我需要的Team點是Players的所有點的總和每個位置陣列。

我目前正在研究的領域是MongoDB聚合函數,特別是$sum,但沒有一個示例包含ref對象。這些對象也需要首先填充,以便可以讀取點值。

我覺得以前肯定有人遇到過這個問題,但我的搜索很遺憾。

回答

0

您可以使用$lookup運算符在ref字段上進行連接。但首先你需要創建一個擁有所有玩家_id的字段,最好的操作符是運算符,該運算符需要兩個或更多個數組,並返回一個包含出現在任何輸入數組中的元素的數組。這是一個$project流水線階段內的理想在這裏你可以與所有玩家裁判的數組字段組合成一個陣列,然後可以denormalise,在爲$lookup準備加入。

考慮以下聚合管道:

Team.aggregate([ 
    { 
    "$project": { 
     "players": { 
     "$setUnion": [ 
      "$goalkeepers", 
      "$defenders", 
      "$midfielders", 
      "$attackers" 
     ] 
     } 
    }  
    }, 
    { "$unwind": "$players" }, 
    { 
    "$lookup": { 
     "from": "players", 
     "localField": "players", 
     "foreignField": "_id", 
     "as": "resultingArray" 
    } 
    }, 
    { "$unwind": "$resultingArray" }, 
    { 
    "$group": { 
     "_id": "$_id", 
     "total": { "$sum": "$resultingArray.points" } 
    } 
    } 
], function(err, result){ 
    console.log(result); 
}); 
+1

非常感謝!我只想說$ lookup需要更新版本的MongoDB。 3.2+我相信。這不適用於2.6.2。 – Harry