Dynamic Query Data/Filter Data on Multiple Fields using GraphQL | MongoDB Mongoose
Tags: query, graphql, mongodb, nestjs
Published: 2022-10-11 08:19:15

---
title: Dynamic Query Data/Filter Data on Multiple Fields using GraphQL | MongoDB Mongoose
published: true
date: 2022-10-05 12:40:47 UTC
tags: query,graphql,mongodb,nestjs
canonical_url: https://medium.com/@haadbaig/dynamic-filter-data-on-multiple-fields-using-graphql-mongodb-mongoose-nestjs-nodejs-4fdf1b0c7cd1
---

![](https://cdn-images-1.medium.com/max/1024/1*ASQgDTBgm0WqW7rZ7Pwi3Q.png)

Query/Filter data with multiple fields using GraphQL is different yet a very interesting task. Filtering through database has always been a simple yet tricky task. And when filtering includes multiple fields and data is being fetched using GraphQL, things get really messy. This article will help you in filtering data on multiple fields using GraphQL, MongoDB and Mongoose. In fact we will query data or filter data by sending fields and their values as input. This kind of functionality is usually used in e-commerce websites where we apply multiple filter like color, price, region, reviews etc. on searched data. I will use NestJS to do this task but the method is same for NodeJS and is similarly applicable for JavaScript based platforms. I will attach the [GitHub](http://github.com/mmhaadb) repo link in the end of the article.

```
**Disclaimer:** I will skip the project creating part to keep the article short and generic for both Nest JS and Node JS, if you are new to NestJS you can see the start of my previous articles where I have mentioned the method to create a project using Nest CLI, I'll mention the link at end.  
```

#### Codebase Explanation:

Here I am using a scenario where we have a database of users and mobile phones. We need to _find all the users who have used specific mobile phone_. An array with names of mobile-phone’s ids is maintained in user schema and a separate table with Mobile Phones is present in DB.

#### Method explanation:

We will send data in form of array from GraphQL client. The data will be processed in such a way that the output will be an object of key-value (field\_name: value) pair.

#### Resolver for Fetching Data from GraphQL:

Lets first write a resolver to fetch data by calling GraphQL API from GraphQL client.

**For NestJS:**

```
@Query(() => [User], {name: "FindWithMultipleFields"})

findWithMultipleFields (
@Args('fields', { type: () => [String]} ) fields: any,
@Args('values', { type: () => [[String]]} ) values: any) {

return this.userService.findWithMultipleFields(fields, values);

}
```

**For NodeJS:**

```
const resolvers = 
{   
Query: {     
findWithMultipleFields(fields, values) {       
return users.findWithMultipleFields(fields, values);     
}}}
```

here for Node, we are using JS classes.

#### **Manipulating Data into key-value Pair:**

Now this is the main part and it is similar for both Node and Nest because it is basic JavaScript task. Now we have out array of _fields_ and array of _values_. We need to process it in such a way that the output is an object of _{field: value}_ pairs.

```
async findWithMultipleFields (fields: any, value: any): Promise<UserDocument[]> {

const result = value.reduce(function(result, field, index) {
result[fields[index]] = field;
return result;
}, {})
return await this.userModel.find(result);

}
```

This code will work in a following way.

```
**Input:** 
field : [model, price]
value: ['Iphone', 20000]

**Output:**  
result: {{model: 'Iphone', price: 20000}} 
```

Since mongoose find function takes an object of key-value pairs, thus we only have to pass the variable **_result_** in Model.find() and we will get the filtered data.

#### Sending Data from GraphQL:

Here I am attaching a screen shot of GraphQL client to showcase the calling of GraphQL API.

![Query Data/Filter Data on Multiple Fields using GraphQL | MongoDB Mongoose](https://cdn-images-1.medium.com/max/1024/1*dy0TbyTUvTAejvPBfTChBA.png)

Here I have passed data in the form of array, even though I am querying on single field here but you can test it and it will for sure work on multiple fields. Output can be seen on the right side of the screenshot attached.

Here is the [**link**](https://github.com/mmhaadb/NestJS-concepts/tree/multiple-field-query-gql)to the final code base, a dummy project that I made to implement this use-case for you.

[GitHub - haadbaig/NestJS-concepts at multiple-field-query-gql](https://github.com/haadbaig/NestJS-concepts/tree/multiple-field-query-gql)

**Conclusion:**

I hope this was useful for you. Querying data from database by filtering on multiple fields is an important simple yet a tricky task, and when GraphQL is added in the stack, it become more tricky, however, I believe that after reading this article it will become understandingly easy for you.

If you liked my writing, and find it helpful, do share it with you fellows and leave a comment and claps for me. Also connect me on my [LinkedIn ](http://linkedin.com/in/haadbaig)profile.

You can also read my previous article on uploading files with GraphQL mutations, here is the link:

[Uploading files using GraphQL Client to MongoDB with NestJS / NodeJS](https://dev.to/haadbaig/uploading-files-using-graphql-client-to-mongodb-with-nestjs-nodejs-16mj-temp-slug-7422414)