Prisma ORM/Cheat sheet/MongoDB
Last edited by dave on 28/10/2025, 13:33:48 UTC
Prisma ORM / Cheat sheet / MongoDB
Contents
Everything you need to know to use MongoDB effectively with Prisma ORM — from setup to modeling, querying, and working with embedded documents.
This guide brings together the flexibility of MongoDB and the type safety of Prisma. 🍃⚡
⚙️ Setup
Install Prisma & MongoDB Driver
npm install prisma --save-dev npm install @prisma/client
Initialize Prisma
npx prisma init
.env
DATABASE_URL="mongodb+srv://user:password@cluster0.mongodb.net/mydb?retryWrites=true&w=majority"
🧱 Prisma Schema for MongoDB
Basic Example
generator client { provider = "prisma-client-js" } datasource db { provider = "mongodb" url = env("DATABASE_URL") } model User { id String @id @default(auto()) @map("_id") @db.ObjectId name String email String @unique posts Post[] } model Post { id String @id @default(auto()) @map("_id") @db.ObjectId title String content String? published Boolean @default(false) authorId String? @db.ObjectId author User? @relation(fields: [authorId], references: [id]) }
⚡ Prisma MongoDB Limitations
Prisma uses MongoDB’s document model under the hood — but with a relational flavor.
✅ Supported:
- Relations (via references)
- Embedded documents
- Arrays & JSON
- Unique indexes
🚫 Not Supported (as of Prisma 5.x):
- Transactions across collections
- Raw aggregation pipelines (must use
$runCommandRaw) - Complex multi-level relations
🔄 Migrations
MongoDB doesn’t use SQL migrations — Prisma simulates them for schema synchronization.
Create Migration (in dev)
npx prisma db push
db pushapplies schema changes directly (no SQL migration files).
Reset Database
npx prisma migrate reset
🧠 CRUD Operations
Create
const user = await prisma.user.create({ data: { name: "Alice", email: "alice@example.com", }, });
Read
const users = await prisma.user.findMany(); const user = await prisma.user.findUnique({ where: { email: "alice@example.com" }, });
Update
await prisma.user.update({ where: { email: "alice@example.com" }, data: { name: "Alice Cooper" }, });
Delete
await prisma.user.delete({ where: { email: "alice@example.com" }, });
🧩 Embedded Documents
MongoDB supports nested objects — Prisma maps them to JSON fields.
model Profile { id String @id @default(auto()) @map("_id") @db.ObjectId userId String @db.ObjectId user User? @relation(fields: [userId], references: [id]) address Address } type Address { street String city String zip String }
Create with embedded type:
await prisma.profile.create({ data: { address: { street: "123 Maple Ave", city: "Toronto", zip: "H0H0H0", }, }, });
🔍 Filtering
const posts = await prisma.post.findMany({ where: { published: true, title: { contains: "Mongo" }, }, });
| Operator | Example | Description |
|---|---|---|
equals | { age: { equals: 30 } } | Exact match |
in / notIn | { role: { in: ["ADMIN", "USER"] } } | Match in list |
lt / lte / gt / gte | { age: { gt: 21 } } | Comparisons |
contains / startsWith | { name: { contains: "bob" } } | String search |
not | { active: { not: true } } | Negation |
🧩 Relations
Connect Related Document
await prisma.post.create({ data: { title: "Hello Mongo", author: { connect: { id: "66f4f0e..." }, }, }, });
Include Relations
await prisma.user.findMany({ include: { posts: true }, });
Nested Writes
await prisma.user.create({ data: { name: "Bob", posts: { create: [ { title: "First Post" }, { title: "Second Post" }, ], }, }, });
🧮 Aggregations
MongoDB support for aggregations in Prisma is limited — but you can still use:
const stats = await prisma.user.aggregate({ _count: true, _min: { name: true }, _max: { name: true }, });
For advanced pipelines, use:
await prisma.$runCommandRaw({ aggregate: "users", pipeline: [ { $group: { _id: "$role", total: { $sum: 1 } } }, ], cursor: {}, });
🧰 Utility Queries
| Function | Example | Description |
|---|---|---|
findMany | await prisma.user.findMany() | Get all |
findUnique | await prisma.user.findUnique() | Find by unique field |
updateMany | await prisma.user.updateMany() | Batch update |
deleteMany | await prisma.user.deleteMany() | Batch delete |
upsert | await prisma.user.upsert() | Update or insert |
count | await prisma.user.count() | Count documents |
🧮 JSON & Arrays
model Product { id String @id @default(auto()) @map("_id") @db.ObjectId tags String[] config Json }
Query Examples
await prisma.product.findMany({ where: { tags: { has: "tech" } }, }); await prisma.product.findMany({ where: { config: { path: ["color"], equals: "blue" } }, });
🧾 Raw MongoDB Commands
For operations beyond Prisma’s ORM layer:
await prisma.$runCommandRaw({ find: "users", filter: { email: "alice@example.com" }, });
Run inserts:
await prisma.$runCommandRaw({ insert: "users", documents: [{ name: "Charlie", email: "c@x.com" }], });
🧭 Pagination & Sorting
const posts = await prisma.post.findMany({ skip: 10, take: 5, orderBy: { createdAt: "desc" }, });
| Option | Description |
|---|---|
skip | Offset |
take | Limit |
orderBy | Sort |
cursor | Cursor-based pagination |
🧠 Transactions (Limited)
MongoDB + Prisma supports single-database transactions only in clusters with replica sets.
await prisma.$transaction(async (tx) => { await tx.user.create({ data: { name: "Batch" } }); await tx.post.create({ data: { title: "Atomic Post" } }); });
🧰 Prisma Studio
Launch a GUI for MongoDB:
npx prisma studio
Opens http://localhost:5555
Browse, edit, and delete documents visually.
🧩 Performance Tips
- Use indexes for frequently queried fields (
@uniqueor@@index). - Use lean models — MongoDB prefers fewer deeply nested documents.
- Avoid unnecessary
includein queries. - Batch operations with
$transactionfor consistency. - Use
db pushinstead of migrations for schema evolution.
🧾 TL;DR Mind Map
| Area | Command / Feature | Description |
|---|---|---|
| Init | npx prisma init | Create Prisma project |
| Schema | provider = "mongodb" | Use MongoDB datasource |
| Deploy | npx prisma db push | Sync schema |
| Query | prisma.user.findMany() | Fetch data |
| Relations | connect, include | Link documents |
| JSON | Json / String[] | Embedded or array fields |
| Raw | $runCommandRaw | Direct MongoDB commands |
| Studio | npx prisma studio | Visual DB browser |
Backlinks (0)
- General
No backlinks yet.
- User
No backlinks yet.
- Redirects
No backlinks yet.
- Media
No backlinks yet.
- Categories
No backlinks yet.
Categories (0)
No categories assigned to this page.
Edit Level
> Signed In Users
Latest on Lounge
Join the conversation about the 'Prisma ORM/Cheat sheet/MongoDB' article →
No comments yet. Be the first to comment!