Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to MongoDB
MongoDB CRUD Operations Guide

MongoDB CRUD Operations Guide

MongoDB2,667 viewsBy Admin
mongodbcrudoperations

Advertisement

CRUD in MongoDB

CRUD = Create, Read, Update, Delete — the four basic operations. MongoDB's methods are intuitive and JSON-based.

Create

db.users.insertOne({ name: "Sara", age: 25 });
db.users.insertMany([{ name: "Ali" }, { name: "Omar" }]);

Read

db.users.find();                          // all
db.users.find({ age: { $gte: 18 } });     // filter
db.users.findOne({ name: "Sara" });       // one
db.users.find().sort({ age: -1 }).limit(5);

Update

db.users.updateOne(
  { name: "Sara" },
  { $set: { age: 26 } }
);
db.users.updateMany({}, { $inc: { age: 1 } });

Delete

db.users.deleteOne({ name: "Sara" });
db.users.deleteMany({ age: { $lt: 18 } });

Common Query Operators

OperatorMeaning
$gt / $ltGreater/less than
$inIn array
$setSet field
$incIncrement

FAQs

insertOne vs insertMany?

One document vs an array of documents. More in our MongoDB section.

How do I update nested fields?

Use dot notation: { $set: { "address.city": "Dubai" } }.

Advertisement