Lecture: Lecture 22 - Introduction to MongoDB
Related: MongoDB Polyglot Persistence Hadoop and Apache Spark · MongoDB Compass and Aggregation Pipelines · NoSQL Data Models MapReduce Rereduce and Views

Terminology mapping and BSON documents (Slides 2–5)

MongoDB is the leading open-source NoSQL document-oriented database, designed for high performance, high availability, native scalability, and flexible data modeling (Slide 2). Mapping relational terms onto MongoDB gives an approximate equivalence (Slide 3):

Relational databaseMongoDB
TableCollection
RecordDocument
ColumnField

Instead of flat table rows, MongoDB stores records as BSON documents—a binary representation of JSON composed of field: value pairs that may be nested (Slide 4). BSON maps naturally into developer-language objects, supporting embedded sub-documents, arrays, Date, NumberLong, and ObjectId:

// Embedded sub-documents (Slide 4)
{
  _id: <ObjectID1>,
  username: "123xyz",
  contact: { phone: 1234567890, email: "xyz@email.com" },
  access:  { level: 5, group: "dev" }
}
 
// Rich BSON types: nested name, dates, array, NumberLong (Slide 4)
{
  _id: ObjectId("5099803df3f4948bd2f98391"),
  name: { first: "Alan", last: "Turing" },
  birth: new Date('Jun 23, 1912'),
  death: new Date('Jun 07, 1954'),
  contribs: [ "Turing machine", "Turing test", "Turingery" ],
  views: NumberLong(1250000)
}

BSON field and document rules (Slide 5)

  • _id primary key: Reserved field name used as the document’s primary key. Its value must be unique within the collection, is immutable, is autogenerated if omitted, and may be of any type other than an array.
  • Null characters: Field names cannot contain the null character.
  • Dots and dollar signs: The MongoDB server permits storage of field names containing . and $ (though query/driver support treats them specially).
  • Duplicate field names: BSON documents technically allow more than one field with the same name, although most client interfaces represent documents as hash tables that do not support duplicate keys.
  • 16 MB size limit and GridFS: The maximum size of a single BSON document is 16 megabytes. To store files/documents larger than 16 MB, MongoDB provides GridFS.
  • Ordered fields: Unlike standard JavaScript objects, fields inside a BSON document are ordered.

Databases and collections (Slides 6–11)

One MongoDB instance manages multiple databases, each containing a set of collections, and each collection holds documents representing similar “objects” (Slide 7). Because MongoDB is schema-less, you do not have to predefine a schema and documents in the same collection may contain different fields—though starting in MongoDB 3.2, you can optionally enforce document validation rules during inserts and updates (Slides 7, 32).

TaskMongoDB shell command (Slides 8–11)Notes
List databasesshow databasesShows available DBs on the instance
Select / switch DBuse deliverydbSelects current database for subsequent commands
List collectionsshow collectionsLists collections in the active DB
Create collectiondb.createCollection("authors", { capped: true })Optional; MongoDB creates collections implicitly when first referenced in a command
Drop collectiondb.authors.drop()Deletes the collection from the active DB
Drop databaseuse deliverydb; db.dropDatabase();Always select the target DB before dropping

CRUD operations (Slides 12–23)

MongoDB’s core shell methods cover Create, Read, Update, and Delete (Slide 12):

OperationSyntax & Source Example (Slides 12–23)Relational / SQL Meaning
Create (one)db.people.insertOne({ user_id: "abc123", age: 55, status: "A" })Inserts a single document; also supports arrays (favorite_colors: ["blue", "green"]) and nested sub-documents (address: { street: "...", city: "..." })
Create (many)db.people.insertMany([{ user_id: "abc123", age: 55, status: "A" }, { user_id: "abc124", age: 45, favorite_colors: ["blue", "green"] }])Inserts multiple heterogeneous documents in one statement
Readdb.users.find({ age: { $gt: 18 } }, { name: 1, address: 1 }).limit(5)SELECT name, address FROM users WHERE age > 18 LIMIT 5 (criteria, projection, cursor modifier)
Updatedb.users.updateMany({ age: { $lt: 18 } }, { $set: { status: "reject" } })UPDATE users SET status = "reject" WHERE age < 18 (update filter + update action)
Delete (filtered)db.people.deleteMany({ status: "D" })DELETE FROM people WHERE status = "D"
Delete (all)db.people.deleteMany({})DELETE FROM people — empty filter {} deletes every document in the collection!

Common confusions

  • Putting an array in _id: _id accepts any BSON type except an array (Slide 5).
  • Forgetting deleteMany({}) deletes everything: Omitting {} raises an error, while passing an empty filter {} matches and deletes all documents in the collection (Slide 23).
  • Assuming BSON fields behave identically to JS object keys: BSON preserves field order and allows duplicate keys at the wire level, even when a client hash-map interface drops duplicates (Slide 5).
  • Thinking createCollection() is mandatory: Collections are created implicitly on the first insert unless you need explicit options like { capped: true } or validation rules (Slides 9–10).

Retrieval questions with answers

1. Why does { _id: ["a", "b"], name: "test" } fail in MongoDB, and how do you store a 50 MB video file alongside document metadata?
_id is MongoDB’s reserved primary key and may be any BSON type except an array. Because a single BSON document has a maximum size of 16 MB, a 50 MB file must be stored using GridFS rather than embedded directly inside one BSON document.

2. Write the MongoDB shell command equivalent to DELETE FROM people WHERE status = "D", and contrast it with deleting every document in people.
Filtered delete: db.people.deleteMany({ status: "D" }). Deleting all documents: db.people.deleteMany({}) (equivalent to DELETE FROM people).

3. In db.users.find({ age: { $gt: 18 } }, { name: 1, address: 1 }).limit(5), what role does each of the three parts play?
{ age: { $gt: 18 } } is the query criteria (SQL WHERE), { name: 1, address: 1 } is the projection (SQL SELECT columns), and .limit(5) is a cursor modifier capping the returned documents (SQL LIMIT 5).