SyntaxStudy
Sign Up
MongoDB Find and Delete Operations
MongoDB Beginner 1 min read

Find and Delete Operations

The find() method returns a cursor of all matching documents, while findOne() returns the first match or null. You can chain cursor methods such as sort(), limit(), and skip() to control how results are returned. Projection (the second argument to find) lets you include or exclude specific fields, reducing the data transferred over the network. deleteOne() removes the first matching document and deleteMany() removes all matches. findOneAndUpdate() and findOneAndDelete() are atomic operations that find a document and modify or remove it in a single step, optionally returning the document before or after the operation — useful for implementing queues or counters.
Example
// find with filter, projection, sort, and pagination
const users = await db.collection('users')
  .find(
    { age: { $gte: 18 } },          // filter
    { projection: { name: 1, email: 1, _id: 0 } }  // projection
  )
  .sort({ name: 1 })   // ascending by name
  .skip(0)             // pagination offset
  .limit(20)           // page size
  .toArray()

// findOne — returns first match or null
const user = await db.collection('users').findOne({ email: "carol@example.com" })

// deleteOne — remove first matching document
const del = await db.collection('users').deleteOne({ email: "old@example.com" })
console.log('Deleted:', del.deletedCount)

// deleteMany — remove all matches
await db.collection('logs').deleteMany({ createdAt: { $lt: new Date('2023-01-01') } })

// findOneAndUpdate — atomic fetch + update (returns updated doc)
const updated = await db.collection('tasks').findOneAndUpdate(
  { status: "pending" },
  { $set: { status: "processing", startedAt: new Date() } },
  { returnDocument: "after", sort: { priority: -1 } }
)