MongoDB is the most widely used document database. Its basic commands are create, read, update and delete (CRUD), run from the shell mongosh or from a program.

Terms

SQL MongoDB
Database Database
Table Collection
Row Document
Column Field

Create

db.supplier.insertOne({ sid: 1, name: "Ravi", city: "Delhi", phone: "98100" });
db.supplier.insertMany([
  { sid: 2, name: "Geeta", city: "Mumbai" },
  { sid: 3, name: "Mike",  city: "Delhi" }
]);

Read

db.supplier.find();                              // all documents
db.supplier.find({ city: "Delhi" });            // equality
db.supplier.find({}, { name: 1, city: 1, _id: 0 }); // only chosen fields
db.supplier.countDocuments();
db.supplier.find().sort({ city: 1 }).limit(2);  // sort and first two

Query operators

Operator Meaning Example
$gt, $gte, $lt, $lte Comparison { price: { $lt: 200 } }
$eq, $ne Equal, not equal { city: { $ne: "Delhi" } }
$in Matches any in a list { color: { $in: ["red", "green"] } }
$and, $or Logical { $or: [{ name: "P1" }, { price: { $lt: 200 } }] }

Update

db.supplier.updateOne(
  { name: "Geeta" },
  { $set: { city: "Bombay", phone: "11223344" } }
);
db.supplier.updateMany({ city: "Delhi" }, { $set: { zone: "North" } });

$set changes only the named fields. Without it, an update document would try to replace the whole record.

Delete

db.part.deleteOne({ pid: 5 });
db.part.deleteMany({ price: { $gt: 5000 } });

Worked example

Show only the name and city of suppliers in Delhi, sorted by name.

db.supplier.find({ city: "Delhi" }, { name: 1, city: 1, _id: 0 }).sort({ name: 1 });

Common mistakes

  • Forgetting that _id is returned unless you turn it off with _id: 0.
  • Using updateOne when you meant to change many documents.

Practice questions

  1. Map the SQL terms table, row and column to MongoDB terms.
  2. Write commands to insert two documents into part.
  3. Write a query for parts with price less than 200 or colour red.
  4. Write a command to change the city of "Geeta" to "Bombay".
  5. Write a command to delete all parts costing more than 5000.

Answers to the practice questions

  1. Collection, document and field.
  2. db.part.insertMany([{pid:1,color:"red",price:150},{pid:2,color:"green",price:300}])
  3. db.part.find({ $or: [{ price: { $lt: 200 } }, { color: "red" }] })
  4. db.supplier.updateOne({ name: "Geeta" }, { $set: { city: "Bombay" } })
  5. db.part.deleteMany({ price: { $gt: 5000 } })

Sources

  • Official BCA syllabus Database Management Systems, course code CC202, Unit IV
  • Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems, 3rd edition, McGraw-Hill