[英]Populate reduce data from one collection to another Meteor Js
I've got a bit of a design issue. 我有一个设计问题。
Say ive got two collections: 说我得到了两个收藏:
Colletion A stores apples ( _id , appleName )
Collection B stores apple votes ( _id , apple_id , enum(0,1) )
I would like to then return collection A with a reduce of collection B based on the apple_id to return the value of 0's to 1's as a property on the main object. 然后,我想基于apple_id返回带有缩减集合B的集合A,以将0的值返回为1的值作为主对象的属性。 ( like a score ) (就像一个分数)
Example data : 示例数据:
collection A array 集合数组
[{_id : 1, appleName : 'grannySmith'},{_id : 2, appleName : 'greenApple'},{_id : 3, appleName : 'anotherApple'}]
collection B array 集合B数组
[{_id : 1, appleId : 1, vote : 0}, {_id : 2, appleId : 1, vote : 1}, {_id : 3, appleId : 1, vote : 1}]
From this Im looking for collection A to return with a reduce of B 从这个我正在寻找集合A以减少B的回报
collection A array with reduce 集合带有reduce的数组
[{_id : 1, appleName : 'grannySmith', score : 2},{_id : 2, appleName : 'greenApple'},{_id : 3, appleName : 'anotherApple'}]
See as it now has a score of 2 from the reduce of collection B with linked IDs 看到它现在从具有链接ID的集合B的缩减中获得了2分
You would use aggregation to achieve it: 您将使用聚合来实现:
db.apple.aggregate([
{
$lookup: {
from: 'score',
localField: '_id',
foreignField: 'appleId',
as: 'scores',
},
}, {
$unwind: {
path: '$scores',
preserveNullAndEmptyArrays: true,
},
}, {
$group: {
_id: '$_id',
appleName: {
$first: '$appleName',
},
score: {
$sum: '$scores.vote',
}
},
}
])
Note: I use $lookup in the first stage of this aggregation, you need to use Mongo 3.2 or above in order for it to work. 注意:我在此聚合的第一阶段使用$ lookup ,您需要使用Mongo 3.2或更高版本才能使其工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.