Overview
MongoDB is a document-oriented NoSQL database. Prisma’s MongoDB connector provides:- Document-based data modeling
- Embedded documents and arrays
- Native MongoDB queries with
findRawandaggregateRaw - Type-safe Prisma Client API
- Support for MongoDB-specific features
Installation
Install the Prisma CLI and Prisma Client:Configuration
Schema configuration
Configure MongoDB in your Prisma schema:Connection configuration
Create aprisma.config.ts file:
Usage
Basic setup
After configuring your schema and connection, generate the Prisma Client:MongoDB-specific features
ObjectId type
MongoDB uses ObjectId for primary keys. Always use@db.ObjectId attribute:
Embedded documents
MongoDB supports embedded documents using composite types:Raw database access
UsefindRaw and aggregateRaw for native MongoDB queries:
Run database commands
Execute MongoDB database commands:Connection string options
MongoDB connection strings support various options:retryWrites=true- Retry write operations on network errorsw=majority- Write concern for data durabilitymaxPoolSize=10- Maximum connection pool sizeminPoolSize=5- Minimum connection pool sizemaxIdleTimeMS=60000- Maximum idle time for connections
Limitations
MongoDB in Prisma has some limitations compared to relational databases:
- No support for referential actions (
onDelete,onUpdate) - No support for scalar lists of enums
- Limited support for filtering on relations
- No support for
@@uniqueon multiple fields containing relation fields
MongoDB Atlas
For production deployments, MongoDB Atlas is recommended:- Create a cluster on MongoDB Atlas
- Whitelist your IP address or use
0.0.0.0/0for all IPs - Create a database user with appropriate permissions
- Get your connection string from the Atlas dashboard
- Replace
<username>,<password>, and<dbname>in the connection string
Best practices
Connection management
Always call
$disconnect() when your application shuts down to properly close connections.Index optimization
Create indexes on frequently queried fields for better performance.
Schema design
Use embedded documents for one-to-many relationships when the child documents are always accessed with the parent.
Next steps
Schema reference
Learn more about MongoDB-specific schema syntax
CRUD operations
Explore MongoDB CRUD operations