GraphQL equivalent Join Query among collections?

I am very new to Graphql. I have a basic question I want to write a GraphiQL query to fetch data among two collections I have a two collections one is Users and other one is Tasks.

Ideally in Sql the same would be written as follows…

SELECT * FROM Users INNER JOIN Tasks ON Users.id = Tasks.user_id

I tried writing in GraphiQl. I also tried adding filters also tried adding relationships. But I always not able to retrieve the data.

{
  users {
    _id  
    tasks {
      
      _id
    }
    
    
  }
}

My collections are as follows. Please let me know if any more info is needed from me?.. Appreciate your help.

Hi @Joel_Fernandes, welcome to the community.
Have tried using $lookup to join two collections? Here’s the syntax for the same:

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

I am not able to find anything mentioned with $lookup in GraphQL docs? I suppose your referring to Mongo Db docs … I am trying to write the query in GraphiQL.

Hi @Joel_Fernandes,
The GraphQL query for your case would look something like this:

{
  users {
    _id  
    tasks {  
      _id
     name
    }
  }
}

Are you using Realm GraphQL or are creating GraphQL on your own using MongoDB?

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha

I am using GraphQL with Realm and Atlas database. Using Apollo Client in javascript with React Js front end.

I get the below error on output…On the sugguested GraphQL solution… I want to know a way to do it without making changes in my schema.

{
  "data": null,
  "errors": [
    {
      "message": "Cannot query field \"tasks\" on type \"User\".",
      "locations": [
        {
          "line": 36,
          "column": 5
        }
      ]
    }
  ]
}

Some additional info … I am using https://www.apollographql.com/. with React js on the front end… Adding relationships to the schema is breaking our Mobile app we are using Realm sync in the mobile app.

Also as per my research I see the below query can lead me to a n+1 problem? as mentioned here Solving the N+1 Problem for GraphQL through Batching

 {
  users {
    _id  
    tasks {  
      _id
     name
    }
  }
}

Hi @Joel_Fernandes,
Yes, it is possible to fetch the tasks associated with a single user.
Follow the following steps to proceed:

1. Create a new function fetchTasks as below:

exports = async function fetchTasks(source, input) {
  const mongodb = context.services.get("mongodb-atlas")
  const tasks = mongodb.db("task-manager").collection("tasks")
  // Replace them with your ^^^^ Database Name and your ^^^^ Collection Name
  return await tasks.find({ user_id: source._id }).toArray()
  // Please note that the above source ^^ is responsible for getting 
  // the details from the parent GraphQL Type (User).
}

2. Now add a new custom resolver from the GraphQL Menu as below:

3. Now we will use the fetchTasks function for this custom resolver:

Enter the following details in their respective input fields:
GraphQL Field Name: tasks
Parent Type: User
Function: fetchTasks
Input Type: None
Payload Type: Select Existing Type(List) and then select [Task]
The form should look something like this once done:


Hit Save Draft.

4. Deploy the changes by clicking on the Review Draft & Deploy

5. Now it’s time to see our queries in action:

 {
  users {
    _id  
    tasks {  
      _id
     name
    }
  }
}

The above GraphQL Query will return the following:

{
  "data": {
    "users": [
      {
        "name": "Sourabh Bagrecha",
        "tasks": [
          {
            "_id": "626f86d5e2a0e2655c95d017",
            "name": "Laundry"
          }
        ]
      }
    ]
  }
}

And yes, this would lead to N+1, and for now there’s no way around that.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
MongoDB

1 Like

Thanks for the valuable information it really does help. Does using the $lookup in the fetchTasks function help us avoid the n+1 problem? … ( I had tried using the $lookup in the custom resolver function and it had worked)… because the n+1 problem is only in Graphql as far as I know… and $lookup is a mongodb function to help us get the combined data . I am not aware if the n+1 problem exists in mongodb … Is that correct?

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.