Skip to content

Updating

import { DriveDB } from '@faeizfurqan/drivedb';
const db = new DriveDB(process.env.DRIVEDB_URL!).db();
const clients = db.collection('clients');
// Change some fields of one document
await clients.updateOne({ name: 'Mei Lin' }, { $set: { status: 'Won' }, $inc: { dealValue: 500 } });
// Change every match
const { modifiedCount } = await clients.updateMany(
{ status: 'Lead' },
{ $set: { status: 'Contacted' }, $currentDate: { lastContactedAt: true } },
);
// Insert when nothing matches (upsert)
await clients.updateOne(
{ email: 'grace@example.com' },
{ $set: { name: 'Grace Hopper', status: 'Lead' }, $setOnInsert: { dealValue: 0 } },
{ upsert: true },
);
// Remove a field's value
await clients.updateOne({ email: 'grace@example.com' }, { $unset: { dealValue: '' } });
// Update and get the result back in one call
const updated = await clients.findOneAndUpdate(
{ email: 'grace@example.com' },
{ $set: { company: 'US Navy' } },
{ returnDocument: 'after' },
);
console.log(modifiedCount, updated?.company);
Operator Does
$set Set fields (new fields are added to the table).
$unset Empty fields.
$inc / $mul Add to / multiply a number.
$min / $max Keep the smaller / larger value.
$rename Move a value to another field.
$push Append to an array ($each for several).
$addToSet Append if not already present.
$pull Remove matching array items.
$pop Remove the first (-1) or last (1) array item.
$currentDate Set to the current date and time.
$setOnInsert Set only when an upsert inserts.

Arrays live in multiple select fields (arrays of strings), link fields (arrays of ids) and JSON fields.

_id, _createdAt and _updatedAt can’t be changed (ImmutableField).

With { upsert: true }, when nothing matches, a document is inserted built from the filter’s equality conditions plus the update:

await clients.updateOne(
{ email: 'grace@example.com' }, // becomes part of the new document
{ $set: { name: 'Grace' }, $setOnInsert: { status: 'Lead' } },
{ upsert: true },
);

The result tells you what happened: { matchedCount, modifiedCount, upsertedId? }.

The first match in the collection’s default order. Pass sort to choose:

await tasks.updateOne({ done: false }, { $set: { owner: 'me' } }, { sort: { priority: -1 } });

Made by Faeiz Furqan