如何限制给定集合的mongodb聚合

时间:2017-08-14 16:20:53

标签: mongodb

以下查询将计算每个国家/地区的GDP总和。 此查询将查看每个国家/地区。 但是让我说我​​想修改这个算法:

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

如何在mongodb中完成?enter image description here

此图片在此处归功于youtube视频: https://www.youtube.com/watch?v=8xiA4i4eepE

1 个答案:

答案 0 :(得分: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 } }

])