简体   繁体   中英

Need a map reduce function in mongo using scala

I am struggling to join two tables in mongodb. I understood from google search that there is no joins concept in mongo. However, we can achieve this by doing map reduce. I am also new to scala. I have two tables in mongodb.

User
    userid
    name
Role
    userid
    permission

I want to combine data from both tables to represent like below

userid, name, permission

Sample Data will be

05533, User1, read
05535, User2, read/write

Can anyone please help to add some sample scala code here to achieve this map reduce functionality?

I tried this below code which works good, but I have millions of records and finding one by one is timing out. First fetch userid from user table and then try to find the corresponding roleid.

              val role = Role.findById(db, userid) match {
                case Some(role) => role
                case None => Role(
                    title = "Role Not Found"
                )
              }

  def findById(db: DaoConnection, id:String) : Option[Role] = {        
    object RoleDAO extends SalatDAO[Role, ObjectId](collection = getCollection(db))        
    RoleDAO.findOne(MongoDBObject("_id" -> new ObjectId(id)));
  }

Instead of querying on scala side, i followed this approach to resolve.

  1. Query user table to get all user details in scala
  2. Query roles table to get all roles in scala
  3. On the client side, map user to role to get the desired output.

This may not the trivial solution, but this is one of the approach suggested forthis kind of issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM