Cheat sheet · Foundations
MongoDB cheat sheet (Java)
Opens with creditsFor students and early-career engineers learning MongoDB from Java, from the first document to data modelling, indexes, aggregation and transactions. Shell snippets are mongosh; application code uses the Java driver and Spring Data MongoDB.
Chapters
8 chapters · 77 concepts
1Documents and your setupWhat a document database is, how MongoDB stores documents in BSON inside collections, and the cluster, shell, GUI and sample data you need before writing real queries.8 concepts
- 1Document modelData stored as documents: self-contained records of field and value pairs that can hold nested objects and arrays, much like JSON.
- 2BSON and its typesBSON is the binary format MongoDB stores and sends documents in.
- 3Database and collectionA database groups collections, and a collection groups documents, roughly like a table groups rows.
- 4ObjectId and _idEvery document has a unique _id field, its primary key.
- 5Atlas free clusterMongoDB Atlas is the hosted MongoDB service.
- 6mongoshThe MongoDB Shell: a JavaScript and Node.js based terminal program that connects to a deployment and runs queries, admin commands and scripts.
- 7MongoDB CompassThe free official GUI for MongoDB: browse collections, edit documents, build aggregation pipelines stage by stage, view explain plans visually and open an…
- 8Sample datasetReady-made databases, such as sample_mflix (films and comments) and sample_airbnb (listings), that Atlas loads into your cluster with one click.
8 in this chapterOpen this chapter2Reading and writing documentsInserting, finding, updating and deleting documents: filters and query operators, projections, sorting and paging, update operators, upserts and cursors.10 concepts
- 1insertOne and insertManyinsertOne adds one document and returns its _id; insertMany adds an array of documents in one round trip.
- 2find and query filtersfind takes a filter document and returns every matching document; findOne returns the first match.
- 3Query operatorsOperators starting with $ express conditions: $eq, $ne, $gt, $gte, $lt, $lte, $in and $nin compare values, $and, $or and $not combine conditions, $exists and…
- 4ProjectionThe second argument to find, listing the fields to return (1) or leave out (0). _id is returned unless you exclude it.
- 5sort, skip and limitCursor methods that order results by one or more fields (1 ascending, -1 descending), skip a number of documents and cap how many come back.
- 6Update operatorsupdateOne and updateMany take a filter and an update document of operators: $set sets fields, $unset removes them, $inc adds to a number, $currentDate stamps…
- 7UpsertAn update with upsert: true inserts a new document when nothing matches the filter, built from the filter and the update. $setOnInsert sets fields only on that…
- 8replaceOne versus updateOnereplaceOne swaps the whole document, apart from _id, for the one you pass. updateOne changes only the fields named by its operators and refuses a plain…
- 9deleteOne and deleteManydeleteOne removes the first matching document and deleteMany removes every match. drop removes the whole collection with its indexes.
- 10Cursorfind returns a cursor, a pointer to the result that fetches documents from the server in batches as you iterate. mongosh prints the first 20; type it for more.
10 in this chapterOpen this chapter- Arrays and nested documentsQuerying and updating fields inside embedded documents and arrays: dot notation, array matching, $elemMatch, array update and positional operators, and the document size limit.6 conceptsOpens with credits
- Data modelling and schema designShaping documents around how the app reads and writes them: embedding versus referencing, relationship sizes, the common schema design patterns, schema validation and the anti-patterns to avoid.12 conceptsOpens with credits
- Indexes and query plansHow indexes make reads fast, which kind to create for which query, how to read explain output, and the habits that keep queries quick as data grows.10 conceptsOpens with credits
- The aggregation pipelineTransforming and summarising documents in stages: filtering, grouping, unwinding arrays, joining with $lookup, multi-facet results, writing results out, the pipeline limits and views.11 conceptsOpens with credits
- MongoDB from your codeUsing MongoDB safely from an application: the driver, connection strings and pooling, schemas in code, injection, duplicate key errors, pagination, change streams and retryable writes.9 conceptsOpens with credits
- Transactions, replication and operationsHow MongoDB keeps data durable and available: write and read concerns, read preference, replica sets, multi-document transactions, sharding, access control, network access, backups and monitoring.11 conceptsOpens with credits
- 9Glossary, A to ZEvery concept in the sheet and the smaller terms it uses, in one list.172 terms
About this sheet
Documents, modelling, indexes, aggregation.
Related on Sefism
Picked from the other libraries by shared topics.
Roadmaps
See allBest practices
See all- PostgreSQL Best PracticesDesign, index, query and run PostgreSQL well: data types, constraints, EXPLAIN, zero-downtime migrations, pooling, transactions, backups and roles.
- MongoDB Best PracticesModel, index, query and run MongoDB well: access-pattern schemas, validation, the ESR rule, aggregation limits, write concern, transactions, drivers and security.
- Data Pipeline Best PracticesHow to build data pipelines you can re-run, test and trust: idempotent tasks, orchestrator hygiene, layered transformations, data tests, freshness, ownership and monitoring.
Checklists
See allProject structures
See all- NestJS project structureFor people who want a structured TypeScript backend with clear rules about where code goes. Every feature is a Nest module that owns its controller, service, DTOs, entities and tests, so the app grows by adding folders, not by stretching old ones. The tree follows one orders API from nest new to a codebase a whole team can run for years.
- FastAPI project structureA typed Python API for an orders app, built the way the FastAPI docs and the official full stack template lay it out: one
apppackage, a router per feature, Pydantic schemas at the edges, services in the middle and SQLAlchemy models with Alembic migrations underneath. For students who have finished the FastAPI tutorial and want to know where the second, tenth and fiftieth file go. - Django project structureFor students building their first serious Python web app or API with Django, and for the team that keeps it running years later. The project is a thin "config" package plus one Django app per business area (accounts, catalog, orders, core), each owning its models, services, views, API, migrations and tests. Settings come from validated environment variables, and the tree grows from the tutorial layout to CI, containers, observability and enforced module boundaries.
Career questions
See all- Should I use PostgreSQL or MongoDB for my project?For most student and startup projects, PostgreSQL is the safer default: relational data, joins, constraints and transactions fit most apps, and it handles JSON and vector search too. MongoDB is a good fit when your data is naturally document-shaped and varies a lot, or your team already knows it well. Model your data first, then choose.
- Should I use Firebase or Supabase for my app?Both let you ship an app fast with auth, a database, storage and hosting-style services. Supabase is built on PostgreSQL, so it suits relational data and SQL skills you will reuse anywhere. Firebase is a mature Google platform with a document database and strong mobile tooling. Choose by your data shape, your platform, and how much you want to learn transferable database skills.
- Do I need a vector database for my AI project?Often not. For a student project or a small app, a vector extension on a database you already use (such as pgvector in PostgreSQL), or even an in-memory index, is enough. A dedicated vector database earns its place with very large collections, heavy query traffic, or features like advanced filtering and multi-tenancy at scale.
Cheat sheets
See all- Choosing the right database cheat sheetSQL, document, cache, search, vector and more.
- SQL and databases cheat sheetQueries, design, indexes, transactions.
- Vector databases cheat sheetEmbeddings, similarity metrics, ANN indexes, filtering, hybrid search, reranking, RAG chunking, pgvector, dedicated stores and evaluation.
Work with me
Stuck on something specific?
Writing only gets you so far. If you want an answer to your situation rather than the general case, book a session and we will work through it together. Sessions are free for approved Sefism members, and a few slots open each week.
- 1:1 Mentorship
- Fresh Graduate Mentorship
- Career Guidance
Brand deals, promos and partnerships: tauseeffayyaz@gmail.com