MongoDB Examples
A handful of MongoDB patterns you reach for over and over - upsert, time series, geospatial, transactions.
MongoDB by example
EXAMPLE
// 1. Upsert
await users.updateOne(
{ email: 'ada@example.com' },
{
$set: { name: 'Ada', updatedAt: new Date() },
$setOnInsert: { createdAt: new Date(), provider: 'email' },
},
{ upsert: true }
);
// 2. Time-series collection (4.4+)
await db.createCollection('metrics', {
timeseries: {
timeField: 'ts',
metaField: 'tags',
granularity: 'seconds',
},
expireAfterSeconds: 60 * 60 * 24 * 30, // 30 days TTL
});
await db.collection('metrics').insertOne({
ts: new Date(),
tags: { host: 'web1', region: 'syd' },
cpu: 0.42,
rss: 184_320_000,
});
// 3. Geospatial queries
await places.createIndex({ loc: '2dsphere' });
await places.insertOne({
name: 'Bondi Beach',
loc: { type: 'Point', coordinates: [151.2766, -33.8908] },
});
const within10km = await places.find({
loc: {
$nearSphere: {
$geometry: { type: 'Point', coordinates: [151.2093, -33.8688] },
$maxDistance: 10_000,
},
},
}).toArray();
// 4. Transactions
const session = client.startSession();
try {
await session.withTransaction(async () => {
await accounts.updateOne({ _id: from }, { $inc: { balance: -amount } }, { session });
await accounts.updateOne({ _id: to }, { $inc: { balance: amount } }, { session });
await ledger.insertOne({ from, to, amount, at: new Date() }, { session });
});
} finally {
await session.endSession();
}
// 5. Aggregation - top spenders this week
const top = await orders.aggregate([
{ $match: { createdAt: { $gte: new Date(Date.now() - 7 * 86_400_000) } } },
{ $group: { _id: '$customerId', total: { $sum: '$total' }, n: { $sum: 1 } } },
{ $sort: { total: -1 } },
{ $limit: 10 },
]).toArray();
// 6. Bulk write
await users.bulkWrite([
{ insertOne: { document: { email: 'a@x' } } },
{ updateOne: { filter: { email: 'b@x' }, update: { $set: { tier: 'pro' } } } },
{ deleteOne: { filter: { _id: someId } } },
], { ordered: false });
Why it matters
These five patterns - upsert, time series, geospatial, transactions, aggregation - cover most of the non-CRUD work you do with Mongo. Bulk writes are the single biggest perf win when you have batch jobs hitting the same collection.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
// See the lesson body for ready-to-paste queries.
print('MongoDB examples');
Try it Yourself »
Discussion
Loading…