How to group data based from two collections in mongodb?

浪子不回头ぞ 提交于 2021-01-28 03:44:41

问题


Following are my two collections

users:{
  _id: "",
  email: "test@gmail.com",
  department: "hr"
}

details:{
  _id: "", 
 email: "abc@gmail.com"
  some_data:[
    {user_email: "test@gmail.com", ....},
    {user_email: "test1@gmail.com", ....},
    {user_email: "test@gmail.com", ....},
  ]

}

What I require is an output saying top 3 departments in the details based on email. Example:

If I query for email: abc@gmail.com, I must get
[
{department: "hr", count: 4},
{department: "finance", count: 3},
{department: "IT", count: 2}
]

I know the db design is horrible but I cannot do anything about it now. So how can this be achieved in MongoDB.

I want the results from details.some_data but grouped based on the departmentfield of users.

来源:https://stackoverflow.com/questions/34441301/how-to-group-data-based-from-two-collections-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!