Export React Filters to a MongoDB Query
Preview visual filter rules as MongoDB query syntax before validating them on your server.
What this recipe builds
- A readable MongoDB export preview.
- Number fields stay as numbers in the generated query.
- Builder data sent to the backend for validation before formatting or execution.
Loading the interactive recipe demo...
Install and imports
Install / imports
npm install @vojtechportes/react-query-builder
Fields and initial query
Typed field configuration
const fields: IBuilderFieldProps[] = [{ field: 'category', label: 'Category', type: 'TEXT' },{ field: 'price', label: 'Price', type: 'NUMBER' },];const initialQuery: DenormalizedQuery = [{type: 'GROUP',value: 'AND',isNegated: false,children: [{ field: 'category', operator: 'EQUAL', value: 'books' },{ field: 'price', operator: 'LARGER_EQUAL', value: 20 },],},];
Builder implementation
React implementation
import '@vojtechportes/react-query-builder/styles.css';import React from 'react';import {Builder,type DenormalizedQuery,type IBuilderFieldProps,} from '@vojtechportes/react-query-builder';import { formatQuery } from '@vojtechportes/react-query-builder/formatQuery';const fields: IBuilderFieldProps[] = [{field: 'category',label: 'Category',type: 'TEXT',operators: ['EQUAL', 'CONTAINS'],},{field: 'price',label: 'Price',type: 'NUMBER',operators: ['EQUAL', 'LARGER_EQUAL', 'SMALLER_EQUAL'],},];const initialQuery: DenormalizedQuery = [{type: 'GROUP',value: 'AND',isNegated: false,children: [{ field: 'category', operator: 'EQUAL', value: 'books' },{ field: 'price', operator: 'LARGER_EQUAL', value: 20 },],},];export const MongoExportFilter = () => {const [query, setQuery] = React.useState(initialQuery);const mongoQuery = formatQuery(query, 'Mongo', { fields });return (<><Builder fields={fields} data={query} onChange={setQuery} /><pre>{mongoQuery}</pre></>);};
Format MongoDB query syntax
Format MongoDB query syntax
const mongoQuery = formatQuery(query, 'Mongo', { fields });await sendToTrustedApi({ query, preview: mongoQuery });
Expected output
{ "$and": [{ "category": { "$eq": "books" } }, { "price": { "$gte": 20 } }] }
Validation and safety
- Do not run the MongoDB object created in the browser.
- On the server, rebuild the query using only fields and operators your application supports.
- Also check value types, limit query size, and add access rules on the server.
Production notes
- Send the original builder data to the server and format it only after validation.
- Decide how filters should handle empty values, arrays, and uppercase or lowercase text.
Related guides
Frequently asked questions
Where should the MongoDB query be checked and run?
On the server. Treat the browser output as input, check every field, operator, and value, then build and run the MongoDB query there.
What if a Builder operator has no MongoDB equivalent?
Support only the operators your app can convert. Show a validation message for the others instead of sending an incomplete query.