HomeJSON ToolsJSON to MongoDB

JSON to MongoDB

Convert any JSON object or array into ready-to-run MongoDB insertOne, insertMany, update, or find queries, TypeScript Mongoose schemas, and MongoDB $jsonSchema validators with BSON type inference.

Convert any JSON object or array into ready-to-run MongoDB insertOne, insertMany, update, or find queries, TypeScript Mongoose schemas, and MongoDB $jsonSchema validators with BSON type inference.

This tool is designed to provide a seamless experience for developers by handling complex operations directly in your browser with maximum speed and security.

100% Private
Instant Results
Customizable
Offline Ready
Dev-Friendly
Easy Export

A JSON to MongoDB converter reads a JSON object or array and generates MongoDB shell commands — either db.collection.insertOne() for a single document or db.collection.insertMany() for an array — that you can execute directly in mongosh, MongoDB Compass, or any MongoDB client to insert that data into a collection.

The reason this is not a completely trivial operation is the relationship between JSON and BSON. MongoDB does not store JSON — it stores BSON, which stands for Binary JSON. BSON is a superset of JSON that adds types JSON does not have: Date, ObjectId, Binary, Decimal128, Timestamp, and Regular Expression. When your MongoDB driver sends a document to the database, it serialises it to BSON. When you query it back, it deserialises from BSON. For most everyday fields this conversion is invisible. A JSON string becomes a BSON UTF-8 string. A JSON integer becomes a BSON int32 or int64. A JSON boolean becomes a BSON boolean. Nested objects and arrays pass through unchanged.

Where you need to pay attention is fields that represent BSON types with no JSON equivalent. Date fields are the most common example. If you insert a date as a plain JSON string — "2019-03-12" — MongoDB stores it as a string and you lose all date arithmetic, comparison, and range query capability. WHERE joinedAt > ISODate("2020-01-01") will not match a string-stored date. The correct insertion syntax is ISODate("2019-03-12T00:00:00Z") or new Date("2019-03-12") in mongosh, which produces a BSON Date object in storage. This converter detects ISO-formatted string values in your JSON and wraps them in the appropriate date constructor automatically.

ObjectId is the other BSON type you encounter constantly. MongoDB's native _id field is an ObjectId — a 12-byte value encoding a timestamp, machine identifier, process ID, and random counter, represented as a 24-character hex string. If your JSON contains an _id field with a hex string value, this converter produces ObjectId("your_hex_string") rather than a plain string, maintaining type consistency with MongoDB's native identity scheme. Fields named with common reference patterns like userId or authorId are also flagged for ObjectId wrapping when their values match the 24-character hex pattern.

This tool takes a JSON object or a JSON array of objects and generates MongoDB shell commands you can run immediately. For a single JSON object, it produces a db.collection.insertOne({...}) call. For a JSON array, it produces a db.collection.insertMany([...]) call containing every element of the array as a separate document. The collection name in the generated command defaults to a sensible name derived from your JSON structure, and you can override it in the collection name field before generating. This is useful when you want the output to target a specific collection in your MongoDB deployment without manually editing the generated command. The BSON type conversion covers the cases that cause silent data corruption when ignored. String values matching the ISO 8601 date format — patterns like "2019-03-12" or "2024-07-15T14:30:00Z" — are wrapped in new Date() in the output, producing a BSON Date type in storage that supports full date range queries and date aggregation pipeline stages like $dateToString, $year, $month, and $dayOfMonth. Plain strings do not support any of these operations. String values matching the 24-character hexadecimal ObjectId pattern are wrapped in ObjectId() in the output. This maintains type consistency with MongoDB's native _id fields and ensures that queries using ObjectId comparison work correctly on those fields. Nested documents and arrays are included as-is in the output. MongoDB's document model natively supports arbitrary nesting depth and mixed arrays, so there is no special handling required — your nested profile object and your tags array both land correctly in the output document structure. The generated command uses mongosh syntax by default, which is the current MongoDB shell introduced in MongoDB 5.x and the replacement for the legacy mongo shell. A legacy mode option produces output compatible with the older mongo shell syntax for developers working with MongoDB 4.x or earlier deployments that have not yet migrated to mongosh. The entire operation runs in your browser. No JSON data is transmitted to any server. You can paste real API payloads, production database documents, or sensitive records without any data leaving your machine.

1. Paste your JSON into the input editor. This can be a single JSON object representing one document, or a JSON array of objects representing multiple documents. Both are handled automatically — the tool detects the input shape and generates insertOne or insertMany accordingly.

2. Set your collection name in the collection name field. The default is derived from your JSON structure, but you almost certainly want to set this to the actual collection name in your MongoDB deployment. This is the only field you must configure before generating.

3. If your MongoDB deployment is running version 4.x or earlier, toggle the Legacy Shell option to produce mongo shell syntax instead of mongosh syntax. If you are using MongoDB 5.0 or later or connecting through Compass, leave this off — mongosh syntax is the current standard.

4. Click Convert to MongoDB Query. The output panel shows the complete insert command with all BSON type conversions applied — ISODate() wrappers on date fields and ObjectId() wrappers on 24-character hex string fields that match the ObjectId pattern.

5. Review the generated command before running it. Check that date fields have been correctly wrapped in new Date() or ISODate(), that your _id field if present is an ObjectId rather than a plain string, and that your collection name in the command matches your target collection exactly.

6. Copy the output and paste it directly into mongosh, the MongoDB Compass shell tab, or any MongoDB client that accepts shell commands. The command is designed to execute without modification in a standard MongoDB environment.

MongoDB's core promise is that it stores documents that look like the JSON your application already works with. That promise is largely true — but there is a gap between raw JSON and the insert commands MongoDB actually needs, and that gap causes problems in practice. The most common problem is dates. Virtually every API that returns records with timestamps returns them as ISO 8601 strings. "createdAt": "2023-09-15T10:22:00Z" looks like a date, feels like a date, and in most application code behaves like a date after you parse it with your ORM or driver. But if you insert it as a raw string into MongoDB, it is stored as text. A query like db.users.find({createdAt: {$gte: new Date("2023-01-01")}}) will return zero results even for documents that clearly have 2023 dates, because MongoDB is doing a string comparison, not a date comparison, and BSON dates and BSON strings are never equal regardless of their content. I have seen this mistake in production codebases more than once. The developer tested with a driver that automatically converted date strings to BSON Dates — and then a manual seed script inserted the same data as raw strings, silently corrupting the entire date range query logic. The second common problem is seeding and migration work. When you are building a new service that consumes a third-party API, you want to capture a sample of the API response and seed your local or staging MongoDB with realistic data. Writing the insertMany command from scratch means manually copying the JSON, formatting it as a MongoDB shell command, handling the collection name, and ensuring BSON types are correct. For a ten-field document with thirty records, that is fifteen minutes of mechanical work that introduces escaping errors and type mistakes. This tool compresses it to thirty seconds. Data migration work has the same pattern. Moving documents from one MongoDB collection to another, or migrating data from a REST API into MongoDB for the first time, involves taking JSON payloads and constructing insertion commands. Having a tool that produces correct, ready-to-run shell commands removes an entire class of manual error. The mongosh vs legacy shell distinction matters more than it sounds for teams with mixed MongoDB versions. MongoDB deprecated the legacy mongo shell in MongoDB 5.0 and removed it entirely in 6.0. Teams still running 4.x deployments — common in enterprise environments with conservative upgrade cycles — need legacy syntax. Having both options in one tool means you do not need to remember which syntax your target environment requires.

Automatic BSON Date wrapping for ISO 8601 string fields — prevents silent date query failures

ObjectId() wrapping for 24-character hex string fields matching the ObjectId pattern

Generates insertOne for single objects and insertMany for arrays automatically

Custom collection name configuration before generating output

Supports both mongosh syntax (MongoDB 5+) and legacy mongo shell syntax (MongoDB 4.x)

Handles arbitrary nesting depth and mixed-type arrays natively

Runs entirely in your browser — zero data transmitted to any server

Free with no account

no install

no rate limits

Seeding a local or staging MongoDB instance with realistic API response data

Bulk importing records from a JSON file or REST API response into a MongoDB collection

Migrating data from a relational database JSON export into MongoDB document format

Building MongoDB insert fixtures for integration and end-to-end test suites

Quickly inserting sample documents into MongoDB Compass during schema exploration

Converting webhook payload samples into insertable MongoDB documents for replay testing

Archiving third-party API responses as structured MongoDB documents

Prototyping a MongoDB data model from an existing JSON data structure

Example Input

{
  "id": 1,
  "name": "Priya Singh",
  "email": "priya@techcorp.io",
  "role": "Principal Engineer",
  "yearsExperience": 15,
  "isActive": true,
  "joinedAt": "2019-03-12T00:00:00Z",
  "lastLogin": "2026-05-28T09:14:33Z",
  "skills": ["MongoDB", "PostgreSQL", "Go", "Rust", "System Design"],
  "profile": {
    "bio": "15 years in distributed systems and data infrastructure.",
    "timezone": "Asia/Kolkata",
    "githubHandle": "priyasingh-eng"
  },
  "teamId": "507f1f77bcf86cd799439011"
}

Example Output

db.users.insertOne({
  "id": 1,
  "name": "Priya Singh",
  "email": "priya@techcorp.io",
  "role": "Principal Engineer",
  "yearsExperience": 15,
  "isActive": true,
  "joinedAt": new Date("2019-03-12T00:00:00Z"),
  "lastLogin": new Date("2026-05-28T09:14:33Z"),
  "skills": ["MongoDB", "PostgreSQL", "Go", "Rust", "System Design"],
  "profile": {
    "bio": "15 years in distributed systems and data infrastructure.",
    "timezone": "Asia/Kolkata",
    "githubHandle": "priyasingh-eng"
  },
  "teamId": ObjectId("507f1f77bcf86cd799439011")
});

MongoServerError: E11000 duplicate key error collection — duplicate key on _id

Fix: Your JSON contains an _id field whose value already exists in the target collection, or two documents in your insertMany array share the same _id. For single documents, either remove the _id field to let MongoDB auto-generate a new ObjectId, or change the _id value to a unique one. For insertMany arrays, add the ordered: false option to skip conflicting documents and continue with the rest: db.collection.insertMany([...], {ordered: false}).

Date range queries return zero results despite matching documents

Fix: Your date fields were inserted as plain strings instead of BSON Date objects. A string '2023-09-15' and a BSON Date are different types — range operators like $gte and $lte on date fields only work with BSON Date values. To fix existing documents, run an update: db.users.find({joinedAt: {$type: 'string'}}).forEach(d => db.users.updateOne({_id: d._id}, {$set: {joinedAt: new Date(d.joinedAt)}})).

ObjectId lookup returns null for a document that clearly exists

Fix: The document's _id or reference field was inserted as a plain string, not as an ObjectId. db.users.findOne({_id: ObjectId('abc123...')}) will not match a document whose _id is stored as the string 'abc123...'. To fix: re-insert the document with the _id correctly wrapped in ObjectId(), or query using the string type: db.users.findOne({_id: 'abc123...'}).

Documents inserted into the wrong collection or database

Fix: The MongoDB shell runs commands against the currently active database. If you did not run use yourDatabase before executing the generated insertMany command, the documents landed in the default test database or whichever database your session was last using. Move them with db.getSiblingDB('correctDb').collection.insertMany(db.wrongCollection.find().toArray()) and then drop the incorrectly populated collection.

SyntaxError: Unexpected token in generated command — paste fails in shell

Fix: Most shell syntax errors when pasting generated MongoDB commands come from smart quotes being substituted by a text editor or IDE before pasting. Ensure you are copying plain text, not rich text. Paste into a plain text editor first to strip formatting, then copy again and paste into the MongoDB shell.

Inserting date fields as plain strings instead of BSON Date objects — this is the single most common MongoDB data model mistake. A string '2023-09-15' and a BSON Date for the same day are completely different types in MongoDB's storage layer. String dates cannot be used in $gte/$lte range queries, $dateToString aggregation, $year/$month/$day pipeline operators, or TTL index expiry. Everything looks correct when you insert and immediately query back the value, because the string representation looks like a date. The bug appears the first time you run a date range query and get zero results despite clearly matching documents.

Leaving _id as a plain string or integer when it should be an ObjectId — MongoDB auto-generates an ObjectId for _id if you omit the field. If your JSON contains an _id field with a 24-character hex string and you insert it as a plain string, your document is stored with a string _id. Queries using ObjectId('your_hex') to look up that document will return nothing, because ObjectId('abc') and the string 'abc' are different BSON types even when the hex content is identical. Always wrap _id hex strings in ObjectId().

Using insertMany with documents that have conflicting _id values — if two documents in your array share the same _id value, MongoDB will insert all documents up to the conflict and then stop, throwing a duplicate key error. Documents after the conflicting _id in the array are silently not inserted. Use insertMany with the ordered: false option if you want MongoDB to skip conflicting documents and continue inserting the rest: db.collection.insertMany([...], {ordered: false}).

Targeting the wrong database — the generated db.collection.insertMany() command runs against whichever database your shell session is currently using. If you have not explicitly switched to the correct database with use myDatabase before running the command, you will insert into the wrong database silently. Always run use yourDatabaseName in your shell session before executing the generated command.

Assuming the collection will be created with a schema validation rule — MongoDB creates collections implicitly on first insert with no schema constraints. Every field is optional, every type is accepted. If you need field-level type enforcement, you need to explicitly create the collection with a validator: db.createCollection('users', {validator: {$jsonSchema: {...}}}) before inserting.

Does it support BSON types like Date and ObjectId?

Yes. String values that match the ISO 8601 date format — patterns like '2023-09-15' or '2024-07-15T14:30:00Z' — are automatically wrapped in new Date() in the generated output, producing a BSON Date type in MongoDB storage. This is critical for correct date range queries, TTL index behaviour, and date aggregation pipeline operations. String values matching the 24-character hexadecimal ObjectId pattern are wrapped in ObjectId(), maintaining type consistency with MongoDB's native _id scheme and ensuring ObjectId-based reference queries work correctly.

Can I specify the collection name?

Yes. The collection name field lets you set the exact target collection name before generating the command. The default is inferred from your JSON structure, but you should always set this explicitly to match your actual MongoDB collection. The collection name appears in the db.collectionName.insertOne() or db.collectionName.insertMany() output — changing it here is faster and safer than editing the generated command manually.

What is the difference between insertOne and insertMany output?

When you paste a single JSON object, the tool generates a db.collection.insertOne({...}) command. When you paste a JSON array of objects, it generates a db.collection.insertMany([...]) command containing every element of the array. insertMany is significantly more efficient than running multiple insertOne calls in a loop — it batches all documents into a single network round-trip to the MongoDB server. For seeding work with dozens or hundreds of documents, always prefer insertMany over looped insertOne calls.

Does it work with mongosh and the legacy mongo shell?

Yes to both. The default output uses mongosh syntax, which is the current MongoDB shell introduced alongside MongoDB 5.0 and the replacement for the deprecated legacy mongo shell. MongoDB removed the legacy mongo shell entirely in version 6.0. If you are working with MongoDB 4.x or an older deployment that has not yet migrated to mongosh, toggle the Legacy Shell option to produce output compatible with the older shell. The difference is primarily in shell-level functions and some method names — the core insert command syntax is identical in both.

Is my JSON data sent to any server?

No. The conversion runs entirely in your browser using JavaScript. Your JSON is never transmitted to any external server, never logged, and never stored anywhere outside your local browser tab. Open your browser's network inspector before pasting any data — you will see zero outbound requests carrying your JSON. This makes the tool safe for real API payloads, production database records, customer data, or any JSON you would not upload to a third-party service.

What happens to nested documents and arrays in my JSON?

Nested objects and arrays are preserved exactly as they are in the generated output. MongoDB's document model natively supports arbitrary nesting depth and mixed-type arrays, so no flattening or transformation is required. A nested profile object becomes an embedded document in the MongoDB document. A skills array of strings becomes a BSON array. A reviews array of nested objects becomes an array of embedded documents. No special handling is needed beyond the BSON type conversions for dates and ObjectIds described above.

How do I handle an _id field in my JSON?

If your JSON contains an _id field with a 24-character hex string value, the tool wraps it in ObjectId() in the generated output. If your _id is a plain integer or a non-hex string, it is preserved as-is — MongoDB accepts any unique value as _id, not just ObjectIds. If you want MongoDB to auto-generate a new ObjectId for every inserted document — the standard approach for new records — remove the _id field from your JSON before generating, or delete it from the generated command before running it.

Can I use the output directly in a Node.js MongoDB driver?

The generated output is MongoDB shell syntax, not Node.js driver code. In the shell, you use db.collection.insertMany([...]). In the Node.js driver (mongodb npm package), the equivalent is await db.collection('users').insertMany([...]). The document structure is identical — you can copy the array of document objects from the generated shell command and use it directly as the argument to insertMany() in your Node.js code. The only difference is the method invocation syntax, not the document content.