Unravel โบ Java concepts โบ NoSQL and caches
MongoDB documents and queries
MongoDB stores JSON-like documents in collections instead of rows in tables.
At a glance
A filing cabinet of folders where each folder holds the whole customer file (address, orders, notes) together, instead of splitting it over many sheets in different drawers.
- 1A class annotated @Document("orders") maps to a collection; the @Id field becomes _id (often an ObjectId or string)Spring Data MongoDB provides repositories exactly like JPA.
- 2Queries use filters: Filters.and(Filters.eq("status", "NEW"), Filters.gt("total", 100)) with the driver, or Query.query(Criteria.where("status").is("NEW")) with MongoTemplate
- 3Updates are partial: Updates.set("status", "SHIPPED"), so you do not rewrite the whole document, and $inc changes counters atomically
- 4The aggregation pipeline (match, group, sort, lookup, project) does server-side analytics in stages
- Design documents around how you read them
- Writes to one document are atomic; changes across documents are not, unless you use multi-document transactions (available, but slower and with limits)
- The driver encodes documents to BSON, the binary JSON format, over a connection pool to the replica set
@Document("orders")public class OrderDoc { @Id private String id; @Indexed private String customerId; private List<LineItem> lines = new ArrayList<>();}List<OrderDoc> open = mongo.find( Query.query(Criteria.where("customerId").is(customerId).and("status").is("OPEN")), OrderDoc.class);- line 1 uses Document, the core of MongoDB documents and queries
- line 5 uses Indexed, the core of MongoDB documents and queries
Read the full explanation (about 1 min)
MongoDB stores JSON-like documents in collections instead of rows in tables. Documents can nest data inside each other, which suits data that is read as a whole but makes cross-document consistency your job.
A mental model
A filing cabinet of folders where each folder holds the whole customer file (address, orders, notes) together, instead of splitting it over many sheets in different drawers.
How it works
A class annotated @Document("orders") maps to a collection; the @Id field becomes _id (often an ObjectId or string). Spring Data MongoDB provides repositories exactly like JPA.
Queries use filters: Filters.and(Filters.eq("status", "NEW"), Filters.gt("total", 100)) with the driver, or Query.query(Criteria.where("status").is("NEW")) with MongoTemplate.
Updates are partial: Updates.set("status", "SHIPPED"), so you do not rewrite the whole document, and $inc changes counters atomically.
The aggregation pipeline (match, group, sort, lookup, project) does server-side analytics in stages.
Going deeper
Design documents around how you read them. Embed data that is read together and changes together; reference data that is shared or grows without bound (an array that grows forever hits the 16 MB document limit).
Writes to one document are atomic; changes across documents are not, unless you use multi-document transactions (available, but slower and with limits). Keep related data in one document where you can.
Without an index, a filter scans the whole collection. Create indexes (@Indexed, compound indexes) for every common filter and sort, and check explain() for collection scans.
Under the hood
The driver encodes documents to BSON, the binary JSON format, over a connection pool to the replica set. Reads go to the primary by default; read preference and write concern (w=majority) decide the trade-off between latency and durability. The server stores documents in the WiredTiger engine with B-tree indexes.
Common mistakes
- Unbounded arrays inside documents.
- Missing indexes for frequent queries.
- Assuming multi-document operations are atomic.
- Treating it as a relational database and normalising everything.
How Unravel recognises it
When you paste code, Unravel looks for these signs of mongodb documents and queries. Spotting them yourself is a good habit when you read unfamiliar code:
- Annotations:
@Document@Indexed@CompoundIndex@TextIndexed - Types:
MongoTemplateMongoClientMongoCollectionMongoDatabaseMongoClientsReactiveMongoTemplateAggregatesFiltersUpdatesBsonDocumentObjectIdMongoOperationsAggregationMongoRepositoryand 3 more
Part of a learning path
- Data stores beyond SQL ยท previous: In-memory caches (Caffeine, Guava, Ehcache) ยท next: Elasticsearch and OpenSearch search
Related concepts
Frequently asked questions
What is MongoDB documents and queries?
MongoDB stores JSON-like documents in collections instead of rows in tables. Documents can nest data inside each other, which suits data that is read as a whole but makes cross-document consistency your job.
What are the most common mistakes with MongoDB documents and queries?
Unbounded arrays inside documents. Missing indexes for frequent queries. Assuming multi-document operations are atomic. Treating it as a relational database and normalising everything.
How can I see MongoDB documents and queries in real code?
Paste your own Java into Unravel and it will point out where mongodb documents and queries appears, explain how it works at the detail level you choose, and draw the flow of the code around it.