将sql查询转换为mongodb以用于以下查询

时间:2017-06-19 23:00:27

标签: sql mongodb

请帮我将以下查询转换为mongo db query

Select u.id, sum(t.duration) from user u, time t where u.id=t.usrid and u.role='careManager' groupby u.id

1 个答案:

答案 0 :(得分:0)

mongo shell是一个javascript解释器,因此在内置的实体之间没有“join”功能。你可能需要迭代user集合中的每一行,然后查询{ {1}}按用户收集,使用mongo的聚合或根据许多内容自行添加值 - 例如数据集的大小。

这是一种方法,它聚合时间实体,然后查找每个用户:

想象一下时间有这些数据:

time

用户有这些数据:

> db.time.find();
{ "_id" : ObjectId("59486011d61e4c5fcd2b0e4f"), "user_id" : "a", "duration" : 200 }
{ "_id" : ObjectId("5948601dd61e4c5fcd2b0e50"), "user_id" : "b", "duration" : 100 }
{ "_id" : ObjectId("59486025d61e4c5fcd2b0e51"), "user_id" : "a", "duration" : 100 }
{ "_id" : ObjectId("5948602fd61e4c5fcd2b0e52"), "user_id" : "a", "duration" : 110 }
{ "_id" : ObjectId("59486038d61e4c5fcd2b0e53"), "user_id" : "c", "duration" : 110 }

查询:

> db.user.find();
{ "_id" : ObjectId("59486073d61e4c5fcd2b0e54"), "role" : "careManager", "user_id" : "a" }
{ "_id" : ObjectId("5948607ad61e4c5fcd2b0e55"), "role" : "careManager", "user_id" : "b" }
{ "_id" : ObjectId("59486088d61e4c5fcd2b0e56"), "role" : "notCareManager", "user_id" : "c" }
> 

输出:

db.time.aggregate([{ $group: {"_id" : "$user_id","time": {$sum: "$duration"}} }]).forEach( function(thisTime) { 
   k = db.user.findOne({"user_id":thisTime._id});

   if(k.role == "careManager"){
      print(thisTime._id + ',' + thisTime.time);
   }
})