Home › Developer Tools › MongoDB Query Tester

MongoDB Query Tester

Try MongoDB queries without a database. Paste documents (or use the sample products and orders), write a find() filter or an aggregation pipeline in normal mongosh syntax, and see the matching documents instantly, stage by stage if you like.

Last updated:

A JSON array is one collection; an object of arrays like {"products": [...], "orders": [...]} gives several collections for $lookup. Extended JSON ($oid, $date) and shell syntax (ObjectId(), ISODate()) both work.

mongosh command

      
Advertisement
Advertisement

How to use the MongoDB Query Tester

  1. Load documents: keep the sample products and orders, paste a JSON array (for example from mongoexport --jsonArray or Compass), or upload a .json file.
  2. Choose find() or aggregate() and pick the collection to query.
  3. Write the query in mongosh syntax, such as { price: { $lt: 50 } }, or click an example chip.
  4. Read the results as JSON or as a table. In aggregate mode, use Show output after to inspect each stage.
  5. Copy the mongosh command to run the same query against your real database.

MongoDB query operator cheat sheet

OperatorMatches documents where…Example
$eq / plain valuethe field equals the value (or an array element does){ status: "shipped" }
$nethe field is not equal, including documents without the field{ status: { $ne: "cancelled" } }
$gt $gte $lt $ltethe value is in a range (same type only){ price: { $gte: 10, $lt: 50 } }
$in / $ninthe value is (not) one of a list{ category: { $in: ["home", "kitchen"] } }
$existsthe field is present (true) or missing (false){ discontinued: { $exists: true } }
$typethe value has a BSON type{ price: { $type: "number" } }
$regex or /re/a string matches a regular expression{ name: /^cast/i }
$and $or $norcombinations of whole filters{ $or: [ { stock: 0 }, { price: { $gt: 70 } } ] }
$notan operator expression is false{ price: { $not: { $gt: 50 } } }
$allan array contains every listed value{ tags: { $all: ["wood", "kitchen"] } }
$elemMatchone array element meets all conditions{ ratings: { $elemMatch: { user: "ana", score: 5 } } }
$sizean array has exactly n elements{ ratings: { $size: 0 } }
$expran aggregation expression is true (compare two fields){ $expr: { $gt: ["$qty", "$stock"] } }

Aggregation stages at a glance

StagePurposeTip
$matchFilter documents with the same syntax as find()Put it first so later stages process fewer documents
$project / $addFieldsReshape: keep, drop, rename or compute fields$addFields keeps every existing field
$groupAggregate by a key with $sum, $avg, $min, $max, $push, $addToSet, $first, $last_id: null groups all documents together
$unwindOutput one document per array elementAdd preserveNullAndEmptyArrays: true to keep empty arrays
$lookupLeft outer join with another collectionThe result is always an array; follow with $unwind for one match
$sort, $skip, $limitOrder and paginateSort on a unique field too for stable paging
$facetRun several sub-pipelines on the same inputGreat for a count plus a page of results in one query
$bucket, $sortByCount, $countHistograms, frequency tables and totals$sortByCount: "$tags" after $unwind ranks tags

Rules that often surprise people

  • Type bracketing: { price: { $gt: "10" } } only compares strings, so it never matches numeric prices. Store and query numbers as numbers.
  • null matches missing: { discontinued: null } returns documents where the field is null or absent. Use { $exists: false } or { $type: "null" } to tell them apart.
  • Projections: you cannot mix 1 and 0 in one projection, except _id: 0. _id is included unless you exclude it.
  • Exact sub-document match: { dims: { w: 12, h: 20 } } requires the same fields in the same order; use dot notation such as { "dims.w": 12 } to match one field.
  • Sorting arrays: an ascending sort on an array field uses its smallest element, a descending sort its largest.
  • Dates: range queries on dates need real dates (ISODate() or {"$date": ...}). ISO strings stored as plain text only compare as strings.

Frequently asked questions

Do I need a MongoDB server to use this?

No. The tester contains its own query engine written in JavaScript that follows MongoDB's matching, projection, sorting and aggregation rules, so it runs in your browser on the documents you paste. Nothing is sent to a server, which also makes it safe for sample data copied from production.

What syntax can I use?

Anything you would type in mongosh: unquoted field names, single or double quotes, regular expressions like /^abc/i, ObjectId("..."), ISODate("..."), new Date(...), NumberInt(...), comments and trailing commas. Strict JSON and MongoDB Extended JSON ($oid, $date, $numberLong) are accepted as well.

How does matching work with arrays?

As in MongoDB, a condition on an array field matches if any element satisfies it, so { tags: "camping" } finds documents whose tags array contains camping. Use $all to require several values, $size for an exact length, and $elemMatch when one element must satisfy several conditions at once. Dot notation such as "ratings.score" reaches into arrays of sub-documents.

How do I join two collections with $lookup?

Paste an object with one array per collection, for example {"orders": [...], "products": [...]}, choose the collection the pipeline runs on, and add a stage like { $lookup: { from: "products", localField: "productId", foreignField: "_id", as: "product" } }. The pipeline form with let and pipeline is supported too.

Will the results be identical to my MongoDB server?

For the supported operators the results follow MongoDB's documented behaviour, including type bracketing in comparisons, null matching missing fields and array sort keys. Differences can appear with features that need a server, such as text or geospatial indexes, collation, $where, writes, and the order of $group output, which MongoDB does not guarantee either. Numbers use JavaScript doubles, so NumberDecimal precision is not kept.

Why does my filter return no documents?

Common causes: comparing a string to a number ("42" does not equal 42 and range operators only compare values of the same type), dates stored as plain strings instead of ISODate or $date values, a field name typo or wrong letter case, or using an operator object where a nested document was meant. The error box explains syntax problems with the line and column.

Can I use my own exported data?

Yes. Paste or upload the output of mongoexport (both --jsonArray and the default one-document-per-line format), Compass exports, or any JSON array. Large files of several megabytes work, but the tester is designed for samples rather than full collections.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

MongoDB ObjectId to TimestampDecode a MongoDB ObjectId to its creation date, or build ObjectIds from dates for range queries.Query CSV with SQLRun SQL on CSV, Excel, JSON and Parquet files in your browser with DuckDB. Join and export.JMESPath TesterEvaluate JMESPath expressions against JSON live, the query language used by the AWS CLI.JSON ViewerExplore JSON as a collapsible tree, search keys and values and copy any node's path.Online Python CompilerRun Python 3 in your browser with input(), numpy, pandas, charts and share links.JSON EditorEdit JSON in a tree and as code side by side: add, rename, drag, change types, undo and download.Unzip FilesOpen and extract ZIP files online.RAR & 7z ExtractorOpen RAR, 7z and other archives online and extract files.Regex TesterTest and debug regular expressions live.File Info ViewerCheck file size, type, date and MD5/SHA hashes.SQLite ViewerOpen .db and .sqlite files in your browser, browse tables and run SQL queries.DOCX ViewerOpen and read Word .docx files in your browser, then print or save them as HTML.EPUB ReaderOpen and read EPUB e-books in your browser with pages, a table of contents and font controls.What Is My BrowserSee your browser, version, OS, engine, screen and which web features it supports.Font ViewerPreview TTF, OTF, WOFF and WOFF2 fonts with sample text, waterfall, glyphs and metadata.Markdown EditorWrite Markdown with a toolbar, live split preview, autosave and .md or HTML export.Regex Cheat Sheet75+ ready-to-use regex patterns for emails, URLs, IPs and dates, each with a live test box.JavaScript Keycode FinderPress any key to see its JavaScript key, code, keyCode, which, location and modifiers.QR Code ScannerScan QR codes with your camera or from an image and safely read the link or text.RAID CalculatorUsable capacity, efficiency and fault tolerance for RAID 0, 1, 5, 6, 10, 50 and 60 arrays.JSONPath TesterTest JSONPath expressions live: filters, slices, wildcards and recursive search, with matches highlighted.Mermaid Diagram EditorWrite Mermaid code and see flowcharts, sequence, Gantt and ER diagrams live. Export SVG or PNG.Country Codes ListSearch ISO 3166 alpha-2, alpha-3 and numeric country codes with calling codes and TLDs.CSS Selector TesterTest CSS selectors on your HTML: highlighted matches, match count and specificity.Git Cheat SheetSearchable Git command reference by task, with copy buttons and an undo/rename/fix wizard.HAR File ViewerOpen a .har file to see a waterfall timeline, headers, bodies, timings and size totals.jq PlaygroundRun jq filters on JSON in your browser with live output, flags and an example library.Markdown Cheat SheetInteractive Markdown syntax reference: edit every example and see the live rendered preview.Regex ExplainerPaste a regular expression and get a plain-English breakdown, railroad diagram and flag notes.XPath TesterTest XPath expressions on XML or HTML: highlighted matches, node paths, values and examples.EML File ViewerOpen .eml email files to read the message, headers and raw source and save attachments.Graphviz Online ViewerWrite Graphviz DOT code and render graphs live; switch layout engines, export SVG or PNG.JavaScript Online CompilerWrite and run JavaScript in your browser with a console, timing, error lines and share links.Jupyter Notebook ViewerOpen .ipynb files and read code, Markdown, math, tables, plots and errors without Python.LaTeX Table GeneratorEdit a table like a spreadsheet or paste from Excel and get LaTeX tabular or booktabs code.Log File ViewerOpen huge log files with level colors, regex and time filters, JSON pretty-print and tail -f.Logic Gate SimulatorBuild logic circuits with AND, OR, NOT, XOR gates and flip-flops; see live outputs and truth tables.MSG File ViewerOpen Outlook .msg emails in your browser: sender, recipients, body, headers and attachments.Lottie ViewerOpen Lottie JSON or .lottie files to play, pause, scrub frames, change speed and see details.Diff ViewerPaste a git diff or .patch file and view it side by side or inline, with file navigation.EditorConfig GeneratorBuild an .editorconfig with indent, charset, line endings and trim rules per file pattern.Folder Compare ToolCompare two folders by file list, size and SHA-256 hash, then open a text diff of changed files.Glob Pattern TesterTest glob patterns like **/*.js, {a,b} and !exclusions against a list of file paths.Semantic Version CalculatorBump, compare, sort and test SemVer versions against npm ^, ~ and x ranges.XSLT TesterRun an XSLT 1.0 stylesheet on XML in your browser and see the output as HTML, XML or text.ASCII Diagram EditorDraw boxes, arrows and text on a character grid and copy plain-text diagrams for code and READMEs.DBF File ViewerOpen dBase .dbf files and shapefile tables, search and sort records, export CSV or XLSX.MBOX File ViewerOpen .mbox mail archives: list and search messages, read them, save attachments, export EML.MDB File ViewerOpen Access .mdb and .accdb databases in your browser: list tables, view rows, export CSV.Shapefile ViewerView zipped shapefiles on a map with the attribute table, then export to GeoJSON or CSV.Online Code EditorVS Code-style editor in your browser: tabs, 50+ languages, find/replace, autosave.Online Hex EditorOpen any file as hex and ASCII, edit bytes, search, inspect values and save the result.PHP Online CompilerRun PHP 8 code in your browser with output, HTML preview, error lines and share links.PlantUML EditorWrite PlantUML and see sequence, class, activity and more diagrams live. Export SVG or PNG.Sorting Algorithm VisualizerWatch bubble, insertion, merge, quick, heap and radix sort step by step with live counters.
See all 53 Code Playgrounds & Testers →