Glossary
133 terms from MongoDB, in plain words, each with the chapter that teaches it.
#
- $addToSet
- An update operator that adds an item to a list only if it isn't already there. Adding the tag "gift" to the mug twice stores it once.
- $all
- A query operator that matches a list containing every value you give, in any order. `{ tags: { $all: ["espresso", "wholesale"] } }` finds ESP-5LB.
- $and
- A query operator that takes a list of filters and matches documents passing all of them. Fields in one filter are already ANDed, so you need it mainly to repeat a key.
- $avg
- An accumulator that averages a field across each group. Priya uses it to get each product's average stars.
- $count
- An accumulator that counts the documents in each group, written `{ $count: {} }`.
- $divide
- An expression that divides its first value by its second, such as cents by 100 to get dollars.
- $elemMatch
- A query operator that requires one single array element to meet all the given conditions. It finds orders with at least 2 of one particular SKU, instead of matching the SKU in one item and the quantity in another.
- $exists
- A query operator that matches documents where a field is present (`true`) or missing (`false`). It answers questions like which products have no roast.
- $group
- An aggregation stage that combines documents into one result per group. Its `_id` says what to group by, and the other fields are accumulators.
- $gt / $gte / $lt / $lte
- Query operators for greater than, greater than or equal, less than and less than or equal. Put two in one document to make a range, such as prices from $10 to $20.
- $in / $nin
- Query operators that match a value that is in, or not in, a list. `{ category: { $in: ["mug", "notebook"] } }` finds mugs and notebooks.
- $inc
- An update operator that adds to a number, or subtracts if the amount is negative. If the field doesn't exist yet, it creates it starting from 0.
- $jsonSchema
- The rule format MongoDB uses to validate documents, which is JSON Schema plus `bsonType` to name BSON types. It goes inside a collection's `validator`.
- $limit
- An aggregation stage that keeps only the first n documents. It's also handy for peeking at a pipeline's output while building it.
- $lookup
- An aggregation stage that joins another collection into the pipeline. It matches `localField` to `foreignField` in the `from` collection and puts the matches in a new array field named by `as`.
- $match
- An aggregation stage that keeps only documents matching a `find`-style filter. Put it first so it shrinks later work and can use an index.
- $max / $min
- Accumulators that keep the largest or smallest value in each group, for example the newest review date.
- $multiply
- An expression that multiplies the values in its array. Sam's report uses it for quantity times price.
- $ne
- A query operator that matches values not equal to the one given.
- $or
- A query operator that takes a list of filters and matches documents passing any of them. Sam uses it for anything out of stock or over $70.
- $project
- An aggregation stage that keeps only the fields you list, which can be renamed or computed with expressions. It works like a projection in `find`.
- $pull
- An update operator that removes every item equal to a value from a list.
- $push
- An update operator that adds an item to the end of a list, even if it's already there.
- $regex
- A query operator that matches text against a regular expression. In mongosh you can write it between slashes, with `i` to ignore case.
- $round
- An expression that rounds a value to a given number of decimal places, such as turning 4.666 into 4.7.
- $set
- An update operator that sets the named fields to new values and leaves all other fields alone. It's the safe everyday way to change a document.
- $set (aggregation)
- An aggregation stage that keeps every field and adds or replaces the ones you give. Unlike `$project`, it doesn't drop other fields.
- $size
- A query operator that matches arrays of an exact length.
- $sort
- An aggregation stage that orders documents, using 1 for ascending and -1 for descending. It works like the cursor's `.sort()`.
- $sum
- An accumulator that adds up values in each group, such as units sold or revenue per SKU.
- $unset
- An update operator that removes a field completely. The value you give it doesn't matter.
- $unwind
- An aggregation stage that turns a document with an array into one document per element. KC-1001 with two items becomes two documents with one item each.
- --dbpath
- A mongod option that names the folder where the server keeps its data. The folder must exist before you start the server.
- _id
- The field every document has, unique within its collection, like a primary key. MongoDB adds an ObjectId if you don't supply one.
A
- Accumulator
- A `$group` field that computes one value from each group's documents, such as `$sum`, `$avg`, `$count`, `$min` or `$max`.
- Aggregation pipeline
- A list of stages run by `aggregate()`, where each stage takes documents in, does one job and passes results on, like an assembly line. Priya and Sam use it for reports.
- Atomic
- Happening completely or not at all, with no client seeing it half done. Every write to a single document is atomic, including its embedded arrays.
- Authentication
- Making every connection log in as a user. Until you turn it on, any program on your computer can change everything.
- authSource
- A connection-string option naming the database that holds the user's login. Users created in `admin` need `authSource=admin`.
B
- Backup
- A copy of your data you can restore after a mistake, such as a `deleteMany({})` with the wrong filter.
- BSON
- MongoDB's storage format, a compact binary form of JSON with extra types such as real dates, different-sized numbers and ObjectIds.
- bsonType
- A `$jsonSchema` keyword naming a BSON type that a field must have, such as `"string"`, `"int"`, `"date"` or `"object"`.
C
- Change stream
- A feed that reports every change to a collection as it happens, so an application can react to inserts, updates and deletes without repeatedly querying.
- Cluster
- A replica set that Atlas runs for you. Kettle & Crane's free Atlas cluster supports transactions too.
- Collection
- A group of documents of the same kind, like a SQL table. The kc database has `products` and `reviews` collections.
- Collection scan (COLLSCAN)
- Reading every document in a collection to answer a query. `explain()` shows it as COLLSCAN, and it's the warning sign that an index is missing.
- collMod
- A database command that changes an existing collection's options, such as adding a validator or setting `validationLevel`.
- Compass
- MongoDB's free graphical app for browsing data and building aggregation pipelines with a mouse. It is an optional alternative to typing commands in mongosh.
- Compound index
- An index on several fields, sorted by the first and then by the second within each first value. Order the fields equality, then sort, then range.
- Connection pool
- Open connections a `MongoClient` keeps and reuses, so queries run without reconnecting. Make one client per app.
- Connection string
- Text that tells a program where the server is, such as `mongodb://127.0.0.1:27017`. It can also carry a username and options.
- countDocuments
- A method that counts the documents in a collection, or only those matching a filter.
- createIndex
- A method that builds an index on the fields you give, using 1 for ascending and -1 for descending, and replies with its name such as `sku_1`.
- CRUD
- The four basic database jobs: create, read, update and delete.
- Cursor
- The result of `find()`: a pointer to the results that fetches documents in batches as you read. It has methods such as `sort`, `skip`, `limit` and `toArray`.
D
- Database
- A group of related collections, such as the shop's `kc`. It's created the first time you store something in it.
- Database Tools
- A separate set of command-line programs including mongodump and mongorestore.
- Database user
- A login that programs use to connect to the database, with roles. It's separate from your Atlas account.
- Document
- A record made of field and value pairs, written like a JavaScript object. Values can be text, numbers, dates, lists or nested objects.
- Dot notation
- A quoted path such as `"roast.level"` that reaches a field inside an embedded object, in filters, projections and updates. It also reaches into arrays, like `"items.sku"`.
- Driver
- The library a program uses to talk to a database. For Node it's the `mongodb` npm package.
- dropIndex
- A method that removes an index by the name `getIndexes()` shows.
- Duplication
- Copying data into another document to read faster, at the cost of keeping copies up to date. An order item keeps the price paid even if Jo later changes the product's price.
E
- E11000
- The error code the server gives when a write would break a unique index. In the Node driver it's a `MongoServerError` with `code` 11000.
- Embedding
- Storing related data inside a document, like an order's items inside the order. It suits data that is small, bounded and read with its parent.
- explain()
- A cursor method that reports how the server ran a query instead of returning documents. You compare `nReturned` with `totalDocsExamined` and check the plan's stage.
- Expression
- An operator that computes a value inside an aggregation stage, such as `$round`, `$multiply` or `$divide`.
F
- FETCH
- A query-plan stage that reads the documents an index scan pointed to. `FETCH` over `IXSCAN` means the index was used.
- Field path
- A string starting with `$`, like `"$stars"`, meaning the value of that field in each document inside an aggregation stage.
- Filter
- A document describing which documents to match, such as `{ category: "mug" }`. An empty filter `{}` matches everything.
- find / findOne
- Methods that read documents using a filter and optional projection. `find` returns a cursor, and `findOne` returns the first match or `null`.
- Flexible schema
- Documents in one collection may have different fields. The mug can have a `color` and no `roast`, but nothing stops a typo unless you add validation.
G
- getIndexes
- A method that lists a collection's indexes. Every collection gets an `_id_` index automatically.
- GridFS
- MongoDB's way to store files larger than the 16 MB document limit. It splits each file into smaller chunks stored as separate documents and reassembles them when the file is read.
- Guarded update
- An update whose filter includes a condition, such as `stock: { $gte: 5 }`, so check and change happen in one atomic step. If `modifiedCount` is 0, the condition failed.
H
- Host addresses (127.0.0.1, 0.0.0.0)
- 127.0.0.1 is your own computer, which is where mongod listens by default. 0.0.0.0/0 means every address on the internet, so keep it out of an Atlas IP access list except for a quick test.
- HTTP status codes
- Numbers an API sends to say how a request went: 201 Created (a review was added), 400 Bad Request (failed validation), 404 Not Found (unknown id or SKU) and 409 Conflict (a duplicate key).
I
- Index
- A sorted list of a field's values pointing at the documents that hold them, so the server can jump to matches instead of reading everything. Each index costs space and slows writes.
- insertOne / insertMany
- Methods that add one document or a list of documents to a collection. They report the new `_id` values.
- IP access list
- The addresses Atlas accepts connections from. Add only your own address, not `0.0.0.0/0`, which means every address.
- IXSCAN
- A query-plan stage showing the server found matches through an index. It is the good sign in `explain()`.
K
- Keyfile
- A shared secret that replica set members use to trust each other. Starting mongod with `--keyFile` also turns on authentication.
L
- lean()
- A Mongoose query method that returns plain objects instead of full Mongoose documents, which is faster for reading.
- Least privilege
- Giving each program only the access its job needs. The shop API gets `readWrite` on `kc` only, and Sam's reports get just `read`.
- load()
- A mongosh function that runs a script file such as `seed.js`. The file name is relative to where you started mongosh.
M
- Model
- In Mongoose, the object you use to query and create documents in a collection, made with `mongoose.model()` from a schema.
- MongoClient
- The driver's class that connects to the server. Make one per app, pick a database with `client.db()` and close it in `finally`.
- mongod
- The MongoDB server program, which stores the data and answers requests. It listens on port 27017 by default.
- MongoDB Atlas
- MongoDB's hosted database service, which runs servers, applies updates and keeps copies of your data. It has a free tier with 0.5 GB of storage.
- mongodb+srv://
- A connection string form that looks up the servers' addresses under a host name, so you never list the cluster's members. Atlas gives you one.
- mongodump / mongorestore
- Tools that write a database or collection to BSON files and load them back. Options like `--drop` replace data, and `--nsFrom`/`--nsTo` restore into a copy.
- Mongoose
- An ODM for Node, built on the driver, where you declare schemas and models and it validates documents before saving.
- MongoServerError
- The error class the Node driver throws for server-side failures. Its `code` tells you which, such as 11000 for duplicate key, 121 for failed validation and 48 for NamespaceExists.
- mongosh
- The MongoDB Shell, a JavaScript prompt where you type commands to the server.
- Multi-document transaction
- Writes across several documents that all succeed together or are all undone, like `BEGIN`/`COMMIT`/`ROLLBACK` in SQL. It needs a replica set and a session.
- Multikey index
- An index on an array field that holds one entry per element. MongoDB makes it automatically when the indexed field contains arrays.
N
O
P
- Paging (skip and limit)
- Cursor methods for showing results a page at a time: `.skip(n)` passes over the first n documents and `.limit(n)` returns at most n, like SQL's `offset` and `limit`. Combine them with `.sort()` for stable pages.
- Prefix
- The first fields of a compound index. Queries on a prefix can use the index, but a query on only a later field can't.
- Primary
- The replica set member that accepts writes. A single-member set on your laptop is its own primary.
- Projection
- The second argument to `find`, which picks the fields to return: 1 includes a field, and `_id` comes back unless you set it to 0.
Q
- Query operator
- A `$` key in a filter, such as `$gt` or `$in`, used in place of an exact value to ask for ranges or lists.
R
- Read concern and write concern
- Settings that control how many replica set members must confirm a read or a write before it counts as done. They let you trade speed against safety.
- Referencing
- Storing another document's key, like a review's `sku`, in its own collection. Unlike a SQL foreign key, the server doesn't check it.
- Regular expression
- A pattern for matching text. In mongosh it's written between slashes, like `/espresso/i`.
- replaceOne
- A method that swaps a whole document for a new one, keeping only `_id`. Fields you leave out are lost, so `$set` is usually safer.
- Replica set
- A group of servers keeping copies of the same data so one can take over if another fails. Transactions need one, even a single-member set on your laptop.
- Role
- A set of allowed actions in a database. The common built-in ones are `read`, `readWrite`, `dbAdmin` and `root`.
- rs.initiate
- A mongosh command that sets up the replica set, run once on a fresh data folder. Without it, inserts fail with `not primary`.
- runCommand
- A mongosh method that sends a raw command to the server, such as `collMod`.
S
- Schema
- In Mongoose, the declared shape of a collection's documents, with each field's type and rules such as `required`, `min` and `default`.
- Schema validation
- Server-side rules, written as a `$jsonSchema`, that every insert and update to a collection must pass, whoever sends it. Failures give `Document failed validation`.
- Session
- The driver's object for a sequence of related operations, made with `client.startSession()`. A transaction runs inside one, and each call needs `{ session }`.
- Sharding
- Splitting a collection's data across several servers so it can grow beyond what one machine can hold. Each server stores only a part of the collection.
- SORT
- A query-plan stage showing the server sorted the matches in memory, which is slow on large results. A compound index that matches the sort removes it.
- Stage
- One step of an aggregation pipeline, such as `$match` or `$group`, which takes documents in, does one job and passes results on.
- Summary field
- A stored total kept on a document so pages needn't recompute it, like a product's `rating: { count, total }`. It must be kept in sync, ideally in a transaction.
T
- Time series collection
- A collection type built for measurements recorded over time, such as sensor readings or prices. It stores and queries timestamped data more compactly and efficiently than an ordinary collection.
- TLS
- The encryption used on network connections. Atlas always encrypts connections with it.
- toArray
- A cursor method that reads all results into an ordinary JavaScript array, which you need to loop with `for...of` or return from a route.
- TTL index
- An index that automatically deletes documents, such as old sessions, after a set time. It is used to expire data that is only useful for a limited period.
- Typed collection
- A collection created with a TypeScript type, like `collection<Product>("products")`, so TypeScript checks filters and results and catches typos.
U
- Unbounded array
- An array that can grow without limit, like all of a popular product's reviews inside it. It slows reads and can hit the 16 MB document limit, so reference instead.
- Unique index
- An index that refuses a second document with the same value, such as one SKU per product. A violation gives error E11000.
- Update operator
- A `$` key in an update that says how to change a document, such as `$set` or `$inc`. An update without one is rejected.
- updateOne / updateMany
- Methods that change the first matching document or every match, using update operators. The result shows `matchedCount` and `modifiedCount`.
- Upsert
- An update that inserts a new document when nothing matches the filter. You request it with `{ upsert: true }`.
V
- validationAction
- A `collMod` option: `"error"` (the default) rejects bad writes, while `"warn"` accepts them and only logs a warning.
- validationLevel
- A `collMod` option: `"strict"` (the default) checks every write, while `"moderate"` skips updates to old documents that already broke the rules.
W
- withTransaction
- A session method that starts a transaction, runs your async function and commits when it finishes. If the function throws, it undoes every write and rethrows.