The hierarchy is short. A deployment holds databases; a database holds collections; a collection holds documents. Databases and collections are created implicitly on first write, which is convenient and means a typo creates a collection rather than failing - a real source of confusion when a count comes back zero.
BSON is not JSON. It is a binary format with a richer type system, and the differences matter:
ObjectIdis a 12-byte identifier containing a 4-byte timestamp, a 5-byte random value and a 3-byte counter. It is the default_id, it is roughly sortable by creation time, and because it embeds a timestamp you can extract a document's creation date from it - useful, and also a small information leak worth knowing about.- Numbers have three types:
int(32-bit),long(64-bit) anddouble. JavaScript has onlydouble, somongoshand JavaScript drivers will silently store a number you meant as an integer as a double.Decimal128is the type for money - exact decimal, 34 digits - and it must be chosen explicitly, because the default for a numeric literal is not it. Dateis a 64-bit millisecond timestamp, always UTC. There is no time-zone-aware date type.nulland missing are different. A field set tonulland a field that is absent both match{field: null}in a query, which is a genuine trap;{field: {$exists: false}}is how you distinguish them.
_id is mandatory, immutable and unique. It is indexed automatically and you cannot drop that index. You may supply your own _id - a natural key, a UUID, a composite object - and doing so saves an index when your natural key is what you look rows up by.
The query surface is operators in a document: comparison ($eq, $gt, $in, $ne), logical ($and, $or, $not), element ($exists, $type), array ($all, $elemMatch, $size) and evaluation ($regex, $expr). Nested fields use dot notation. The one to learn properly is $elemMatch: {"items.price": {$gt: 10}, "items.qty": {$lt: 5}} matches a document where some item is over 10 and some item is under 5 - not necessarily the same item. $elemMatch is how you require both conditions on one array element, and the difference is a bug that passes review.
Laboratory exercise 1 - provision and verify a replica set.
Stand up a three-node replica set, not a standalone server - several later modules need one. Initiate it, confirm the member states, and identify the primary.
Create a database and a collection, and load at least 500,000 synthetic documents with realistic nesting: a customer with an address sub-document and an array of tags.
Then demonstrate the type traps, each with evidence: insert a number from mongosh and show it stored as a double; store a price as Decimal128 and as a double and show the arithmetic differ; insert a document with null and one with the field absent and show one query matching both; and write a two-condition array query both with and without $elemMatch, showing the different result sets.
Deliverable: an idempotent setup script, a README taking a colleague from nothing to a loaded replica set, the rs.status() output with the member states explained, and the four type and query demonstrations with their actual output.
// ------------------------------------------------------------------
// A three-node REPLICA SET, not a standalone. Transactions, change
// streams and read concerns do not exist without one.
// ------------------------------------------------------------------
// mongod --replSet rs0 --port 27017 --dbpath /data/rs0-0
// mongod --replSet rs0 --port 27018 --dbpath /data/rs0-1
// mongod --replSet rs0 --port 27019 --dbpath /data/rs0-2
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "localhost:27017", priority: 2 },
{ _id: 1, host: "localhost:27018" },
{ _id: 2, host: "localhost:27019" }
]
});
rs.status().members.map(m => ({
name: m.name, state: m.stateStr, health: m.health,
lagSeconds: m.optimeDate ? (new Date() - m.optimeDate) / 1000 : null
}));
// PRIMARY takes writes. SECONDARY replicates. If you see
// STARTUP2 it is still doing an initial sync; RECOVERING
// cannot serve reads.
use shop;
// ------------------------------------------------------------------
// BSON types. The ones that surprise people.
// ------------------------------------------------------------------
db.typedemo.insertOne({
_id: ObjectId(), // 12 bytes: timestamp + random + counter
plainNumber: 42, // from mongosh this is a DOUBLE, not an int
explicitInt: NumberInt(42),
explicitLong: NumberLong("9007199254740993"),
// Decimal128 is THE money type. Exact decimal, 34 digits. It must be
// chosen explicitly - a numeric literal never gives you one.
price: NumberDecimal("19.99"),
priceAsDouble: 19.99,
when: new Date(), // 64-bit ms, always UTC. No tz-aware type.
tags: ["new", "sale"]
});
db.typedemo.findOne({}, {plainNumber: 1, explicitInt: 1, price: 1});
db.typedemo.aggregate([{$project: {
t_plain: {$type: "$plainNumber"}, // "double" <- not what you meant
t_int: {$type: "$explicitInt"}, // "int"
t_price: {$type: "$price"} // "decimal"
}}]);
// The arithmetic difference, which is the whole reason for Decimal128:
db.typedemo.aggregate([{$project: {
decimalSum: {$add: ["$price", NumberDecimal("0.01")]}, // 20.00 exactly
doubleSum: {$add: ["$priceAsDouble", 0.01]} // 20.000000000000004
}}]);
// ObjectId embeds a creation timestamp - useful, and a small leak:
ObjectId("655f1a2b3c4d5e6f7a8b9c0d").getTimestamp();
// ------------------------------------------------------------------
// null vs MISSING. A real trap.
// ------------------------------------------------------------------
db.nulldemo.insertMany([
{_id: 1, email: "a@example.test"},
{_id: 2, email: null},
{_id: 3} // field absent entirely
]);
db.nulldemo.find({email: null}).toArray(); // matches 2 AND 3
db.nulldemo.find({email: {$exists: false}}).toArray(); // only 3
db.nulldemo.find({email: {$type: "null"}}).toArray(); // only 2
// `{email: null}` meaning "null or missing" is correct behaviour and
// almost never what the person writing it intended.
// ------------------------------------------------------------------
// Synthetic data: mongosh is JavaScript, so just write the loop.
// ------------------------------------------------------------------
const batch = [];
for (let i = 1; i <= 500000; i++) {
batch.push({
email: `c${i}@example.test`,
name: `Customer ${i}`,
creditLimit: NumberDecimal((Math.random() * 50000).toFixed(2)),
address: { city: ["London","Berlin","Austin"][i % 3], country: "GB" },
tags: i % 7 === 0 ? ["vip","newsletter"] : ["newsletter"],
createdAt: new Date(Date.now() - Math.random() * 3.15e10)
});
if (batch.length === 10000) { db.customer.insertMany(batch); batch.length = 0; }
}
if (batch.length) db.customer.insertMany(batch);
// ------------------------------------------------------------------
// $elemMatch - the difference that is a bug which passes review.
// ------------------------------------------------------------------
db.orders.insertOne({_id: 1, items: [
{sku: "A", price: 50, qty: 10},
{sku: "B", price: 5, qty: 1}
]});
// "an item over 10 AND an item under 5 qty" - matches, because
// different array elements satisfy each condition:
db.orders.find({"items.price": {$gt: 10}, "items.qty": {$lt: 5}}).count(); // 1
// "ONE item that is over 10 AND under 5 qty" - does not match:
db.orders.find({items: {$elemMatch: {price: {$gt: 10}, qty: {$lt: 5}}}}).count(); // 0
// ------------------------------------------------------------------
// CRUD, and the flags worth knowing.
// ------------------------------------------------------------------
db.customer.updateOne(
{email: "c1@example.test"},
{$set: {"address.city": "Manchester"}, $inc: {loginCount: 1},
$addToSet: {tags: "vip"}}, // $push would duplicate
{upsert: true}
);
db.customer.updateMany({tags: "newsletter"}, {$set: {optedIn: true}});
db.customer.findOneAndUpdate(
{email: "c2@example.test"},
{$set: {status: "active"}},
{returnDocument: "after"} // atomic read-modify-write
);
db.customer.bulkWrite([
{insertOne: {document: {email: "new@example.test", name: "New"}}},
{updateOne: {filter: {email: "c3@example.test"}, update: {$set: {vip: true}}}},
{deleteOne: {filter: {email: "old@example.test"}}}
], {ordered: false}); // unordered: continues past a failure, and
// runs in parallel. Faster, and the error
// report is a list rather than a stop.
Open this example in the editor and change it. Nothing you type is saved.
Discussion
No questions on this topic yet. Sign in to ask the first one.