file-json-db

Update Operators

Update operators tell the library how to change a document. They are passed as the second argument to updateOne, updateMany, and their async counterparts.

$set – set field values

Replace the value of one or more fields. Creates the field if it does not exist.

users.updateOne(
  { email: 'alice@example.com' },
  { $set: { age: 29, lastLogin: new Date().toISOString() } }
);

// Nested fields work with dot notation
users.updateOne(
  { _id: 1 },
  { $set: { 'profile.city': 'Lagos', 'profile.country': 'NG' } }
);

$inc – increment a number

Add a number to an existing numeric field (or start from 0 if missing).

// Give Alice 10 more points
users.updateOne(
  { name: 'Alice' },
  { $inc: { points: 10 } }
);

// Decrease stock by 1
products.updateOne(
  { sku: 'WIDGET-001' },
  { $inc: { stock: -1 } }
);

$push – append to an array

Push a value onto the end of an array field. Creates the array if it does not exist.

users.updateOne(
  { name: 'Alice' },
  { $push: { tags: 'admin' } }
);

// Push an object
orders.updateOne(
  { _id: orderId },
  { $push: { events: { type: 'shipped', at: new Date().toISOString() } } }
);

$pull – remove from an array

Remove elements that match a value or a sub-document.

// Remove a simple value
users.updateOne(
  { name: 'Alice' },
  { $pull: { tags: 'admin' } }
);

// Remove objects that match certain fields
orders.updateOne(
  { _id: orderId },
  { $pull: { items: { productId: 42 } } }
);

$unset – remove a field

Delete a field from the document.

users.updateOne(
  { name: 'Alice' },
  { $unset: { temporaryToken: 1 } }
);

// Nested field
users.updateOne(
  { _id: 1 },
  { $unset: { 'profile.oldAddress': 1 } }
);

Combining operators

You can use several operators in a single update:

users.updateOne(
  { email: 'alice@example.com' },
  {
    $set:  { lastLogin: new Date().toISOString() },
    $inc:  { loginCount: 1 },
    $push: { loginHistory: new Date().toISOString() },
    $unset: { resetToken: 1 }
  }
);

updateFunc – custom logic

When the operators are not enough, pass a function that receives the document and returns the modified document:

users.updateFunc(
  { role: 'member' },
  (doc) => {
    doc.points = (doc.points || 0) + 5;
    if (doc.points >= 100) {
      doc.role = 'gold';
      doc.tags = doc.tags || [];
      if (!doc.tags.includes('gold')) doc.tags.push('gold');
    }
    return doc;
  },
  { multi: true }   // apply to all matches; omit or false for first only
);
Indexes stay in sync After any update the library automatically refreshes the secondary indexes for the affected documents.