2017-08-14 72 views

回答

3

如果您想通過country,以濾除sum(GDP)然後分組之前增加一個比賽階段。例如:

db.world_gdp.aggregate([ 

    // focus on BR, CN and UK countries ... the subsequent stages in the 
    // pipeline will only get docs for these countries 
    { $match: { country: { $in: ['BR', 'CN', 'UK'] } } }, 

    // group by country and sum GDP 
    { $group: { _id: "$country", gdp: { $sum: "$gdp"} } }, 

    // restrict to those countries having sum(GDP) >= 2500 
    { $match: { gdp: { $gte: 2500 } } }, 

    // sort by sum(GDP) 
    { $sort: { gdp: -1 } } 

]) 

或者,如果你有興趣在過濾通過country,而不是通過過濾sum(GDP)然後試試這個:

db.world_gdp.aggregate([ 

    // focus on BR, CN and UK countries ... the subsequent stages in the 
    // pipeline will only get docs for these countries 
    { $match: { country: { $in: ['BR', 'CN', 'UK'] } } }, 

    // group by country and sum GDP 
    { $group: { _id: "$country", gdp: { $sum: "$gdp"} } }, 

    // sort by sum(GDP) 
    { $sort: { gdp: -1 } } 

])