Understanding CRUD and MongoDB Documents
CRUD stands for Create, Read, Update, and Delete. These four operations form the foundation of database interaction.
MongoDB implements CRUD operations against collections of BSON documents. Each operation has its own behavior, options, return values, and failure scenarios.
1. Create
Create operations insert new documents into a collection.
Common methods:
insertOne()inserts one document.insertMany()inserts multiple documents.
Example:
db.students.insertOne({
name: "Arun",
age: 22
});
2. Read
Read operations retrieve documents that match a filter.
Common methods:
find()returns a cursor for matching documents.findOne()returns one matching document or null.
Example:
db.students.find({ age: { $gte: 18 } });
3. Update
Update operations modify existing documents.
Common methods:
updateOne()modifies at most one matching document.updateMany()modifies all matching documents.replaceOne()replaces the contents of one matching document, apart from the immutable_idbehavior and other operation constraints.
Example:
db.students.updateOne(
{ name: "Arun" },
{ $set: { age: 23 } }
);
4. Delete
Delete operations remove documents that match a filter.
Common methods:
deleteOne()deletes at most one matching document.deleteMany()deletes all matching documents.
Example:
db.students.deleteOne({ name: "Arun" });
CRUD operations are not interchangeable
A read operation does not modify stored data. An update operation can modify selected fields without replacing the entire document. A replacement operation replaces the document's non-_id contents. A delete operation removes matching documents.
Understanding these differences prevents common mistakes, particularly when updating production data.
Atomicity
MongoDB guarantees atomicity at the individual-document level. An update that modifies several fields within one document is atomic as a single-document write. Multi-document operations such as updateMany() are not atomic as a whole unless they are executed within a transaction.
This distinction matters when an application modifies related data across multiple documents.
insertOne, insertManyfind, findOneupdateOne, updateMany, replaceOnedeleteOne, deleteMany- CRUD stands for Create, Read, Update, and Delete.
- MongoDB CRUD methods operate on collections of documents.
- Update operations can modify selected fields without replacing the whole document.
- Replacement operations have different semantics from modifier updates.
- MongoDB guarantees atomicity for individual-document writes, not automatically for an entire multi-document operation.
Which statement about MongoDB updateMany() is correct?