MongoDB聚合管道模拟用于带有substr操作的SQL查询

时间:2016-08-05 17:44:29

标签: mongodb mongodb-query aggregation-framework

MongoDB等效于

SELECT state, SUM(pop) AS totalPop
FROM zipcodes
GROUP BY state
HAVING totalPop >= (10*1000*1000)

db.zipcodes.aggregate( [
   { $group: { _id: "$state", totalPop: { $sum: "$pop" } } },
   { $match: { totalPop: { $gte: 10*1000*1000 } } }
] )

如何在涉及substr操作的SQL查询中获取MongoDB等效项

SELECT substr(state,0,3), SUM(pop) AS totalPop
FROM zipcodes
GROUP BY substr(state,0,3)
HAVING totalPop >= (10*1000*1000)

1 个答案:

答案 0 :(得分:1)

您可以在聚合管道末尾的status字段和$substr阶段使用$project字符串聚合运算符来获取所需的输出

db.zipcodes.aggregate([
  { $group: { "_id": { $substr: [ "$state", 0, 3 ] }, "totalPop": { $sum: "$pop" } } },
  { $match: { "totalPop": { $gte: 10*1000*1000 } } },
  { $project: { "state": "$_id", "totalPop": 1, "_id": 0  } }
]);