Skip to content
Back to Learn
·6 min read

JSON and MongoDB Integration: Working with Documents

MongoDB is a document database that stores data in BSON (Binary JSON) format, making JSON integration seamless and powerful. This guide covers MongoDB-JSON patterns including CRUD operations, aggregation pipelines, schema validation, indexing JSON fields, and data migration. Use our JSON Validator to prepare data before insertion and JSON Formatter to format MongoDB query results.

MongoDB and BSON

MongoDB stores documents in BSON (Binary JSON), a binary-encoded serialization of JSON-like documents. BSON extends JSON with additional data types including ObjectId, Date, Binary, Int32, Int64, and Decimal128. This means MongoDB can handle types that JSON cannot natively represent.

JSON TypeBSON TypeMongoDB Example
stringString (UTF-8){"name": "Alice"}
numberDouble, Int32, Int64, Decimal128{"age": 30, "price": NumberDecimal("19.99")}
booleanBoolean{"active": true}
nullNull{"field": null}
arrayArray{"tags": ["a", "b"]}
objectObject (embedded document){"address": {"city": "NYC"}}
N/AObjectId{"_id": ObjectId("...")}
N/ADate{"createdAt": ISODate("2025-01-15")}

CRUD Operations with JSON

// Insert a JSON document
db.users.insertOne({
  name: "Alice",
  email: "alice@example.com",
  age: 30,
  address: { city: "NYC", zip: "10001" },
  tags: ["developer", "mongodb"],
  createdAt: new Date()
});

// Insert multiple documents (from JSON array)
db.users.insertMany([
  { name: "Bob", email: "bob@example.com", age: 25 },
  { name: "Charlie", email: "charlie@example.com", age: 35 }
]);

// Query with JSON-like syntax
db.users.find(
  { age: { $gte: 25, $lte: 35 }, "address.city": "NYC" },
  { name: 1, email: 1, _id: 0 }
).sort({ name: 1 }).limit(10);

// Update specific JSON fields
db.users.updateOne(
  { email: "alice@example.com" },
  { $set: { age: 31, "address.zip": "10002" } }
);

// Delete by JSON query
db.users.deleteMany({ age: { $lt: 18 } });

Aggregation Pipeline

// MongoDB aggregation with JSON stages
db.orders.aggregate([
  // Stage 1: Filter (match) - like WHERE
  { $match: { status: "completed", total: { $gte: 100 } } },

  // Stage 2: Group by field
  { $group: {
    _id: "$customerId",
    totalSpent: { $sum: "$total" },
    orderCount: { $sum: 1 },
    averageOrder: { $avg: "$total" }
  }},

  // Stage 3: Sort results
  { $sort: { totalSpent: -1 } },

  // Stage 4: Limit to top 10
  { $limit: 10 },

  // Stage 5: Lookup (join with customers collection)
  { $lookup: {
    from: "customers",
    localField: "_id",
    foreignField: "_id",
    as: "customer"
  }},

  // Stage 6: Shape the output
  { $project: {
    customerName: { $arrayElemAt: ["$customer.name", 0] },
    totalSpent: 1,
    orderCount: 1,
    averageOrder: { $round: ["$averageOrder", 2] }
  }}
]);

Schema Validation with JSON Schema

// MongoDB schema validation using JSON Schema (MongoDB 5+)
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email"],
      properties: {
        name: {
          bsonType: "string",
          description: "must be a string and is required"
        },
        email: {
          bsonType: "string",
          pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
        },
        age: {
          bsonType: "int",
          minimum: 0,
          maximum: 150
        },
        address: {
          bsonType: "object",
          properties: {
            city: { bsonType: "string" },
            zip: { bsonType: "string" }
          }
        }
      }
    }
  }
});

Indexing JSON Fields

// Single field index on JSON property
db.users.createIndex({ "address.city": 1 });

// Compound index on multiple fields
db.users.createIndex({ "address.city": 1, age: -1 });

// Text index for full-text search
db.users.createIndex({ name: "text", "address.city": "text" });

// Wildcard index for unknown field paths
db.users.createIndex({ "metadata.$**": 1 });

// 2dsphere index for geospatial JSON data
// {"location": {"type": "Point", "coordinates": [-73.97, 40.77]}}
db.users.createIndex({ location: "2dsphere" });

Integrating with MongoDB Drivers

// Node.js driver
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('mydb');
const collection = db.collection('users');

// Insert JSON directly
await collection.insertOne({
  name: "Alice",
  email: "alice@example.com"
});

// Read JSON from file and insert
const fs = require('fs');
const users = JSON.parse(fs.readFileSync('users.json', 'utf-8'));
await collection.insertMany(users);

// Python driver
from pymongo import MongoClient
import json
client = MongoClient('mongodb://localhost:27017')
db = client.mydb
with open('users.json') as f:
    users = json.load(f)
db.users.insert_many(users)

Next Steps

Validate JSON before MongoDB insertion with JSON Validator. Format results with JSON Formatter. Generate Mongoose schemas with JSON to Mongoose Schema.