2017-08-14 4 views
0

次のクエリは、国あたりのGDPの合計を計算します。 このクエリは各国を調べます。 しかし、私はこのアルゴを変更したいと言うことができます:与えられたセットのmongodb集約を制限する方法

Find gdp for a given subset of countries {BR, CN and UK} only

どのようにこれはMongoDBの中で行うことができますか? enter image description here

この写真は、ここでユーチューブの動画に入金されます。 https://www.youtube.com/watch?v=8xiA4i4eepE

+0

は、あなたがしてください、実行されているクエリを投稿することができますか? – robjwilkins

答えて

3

あなたはsum(GDP)によってcountryでフィルタしたい場合は、グループ化する前に、一致段階を追加します。たとえば:

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 } } 

]) 

それとも、あなたはsum(GDP)によって代わりフィルタリングのcountryによるフィルタリングに興味があるならば、この試してみてください。

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 } } 

]) 
関連する問題