MongoDB
Beginner
1 min read
Find and Delete Operations
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 } }
)