Notes from MongoDB Basics Course

Mehmet Akcay
5 min readMar 1, 2021
  • Database is a structured way of storing to store and get the data. While relational databases do it in rows and columns of tables, NoSQL databases still structures their data but do it without using tables. MongoDB uses documents to store the data, so basically it is a NoSQL document database.
  • A document is a way to handle data as a set of field-value pairs, a collection is a store of documents, and a database contains multiple collections. A document example is as follows:
{
<field> : <value>,
"name" : "Mehmet",
"surname" : "Akçay",
"age" : 31
}
  • Replica set is a few connected machines that have the same data. If something happens to one of them, the other will make sure everything’s running smoothly.
  • Cluster is a group of servers that store the data.
  • A documents in MongoDB are like JSONs but different. JSONs are text based which is costly for parsing, space consuming and only allows only limited number of basic data types. So MongoDB decided to use a changed version of JSON called BSON (Binary JSON). It is in the binary format as the name indicates, supports String, Boolean, Number, Array, Date, Raw Binary some of which are not supported in the original JSON, and the readability by a human is not a main concern so formatting and spaces are reduced.
  • Databases in MongoDB are stored in BSON and viewed in JSON.
  • There are couple of ways to import and export data from shell. mongoimport and mongoexport uses JSON files to import and export data respectively, whereas mongodump and mongorestore uses BSON.
mongodump --uri "mongodb+srv://<your username>:<your password>@<your cluster>.mongodb.net/sample_supplies"  mongoexport --uri="mongodb+srv://<your username>:<your password>@<your cluster>.mongodb.net/sample_supplies" --collection=sales --out=sales.json  mongorestore --uri "mongodb+srv://<your username>:<your password>@<your cluster>.mongodb.net/sample_supplies"  --drop dump  mongoimport --uri="mongodb+srv://<your username>:<your password>@<your cluster>.mongodb.net/sample_supplies" --drop sales.json
  • Namespace is the concatenation of the database name and collection name.
show dbs  -- lists databasesuse sample_training  --chooses a database

show collections
db.zips.find({"state": "NY"})
-- finds documents with query details
--db points to sample_training since we chose to use it above
db.inspections.insert([{ "_id": 1, "test": 1 },{ "_id": 1, "test": 2 }, { "_id": 3, "test": 3 }],{ "ordered": false })
--ordered part is optional
  • Every document must have a unique _id value of type ObjectId.
  • Ordered feature in the insert command is optional. If not assigned to false, the inserts are applied in the same order they’re specified, and if there is an exception during the insertion of any one of them, the rest is not executed. But if assigned to false, execution doesn’t stop.
  • If insertion is done to a collection that doesn’t exist, a collection is created with the specified name and documents are inserted there. The same things goes for use db command.
db.zips.updateMany({ "city": "HUDSON" }, { "$inc": { "pop": 10 } })
  • The above query finds all zips document with city Hudson and increases their population by 10.
db.zips.updateOne({ "zip": "12534" }, { "$set": { "pop": 17630 } })
  • This one updates the first document it finds in the zips collection with zip code 12534 and sets its population to 17630.
db.grades.updateOne({ "student_id": 250, "class_id": 339 },                     { "$push": { "scores": { "type": "extra credit",                                              "score": 100 }                                 }                      })
  • If the field we want to update in the document is an array and we want to add an element to it, we use the push function as shown above which adds an object to the scores array.
  • If ‘…One’ operations are not used in conjunction with _id field, the document which the operation will be applied on is not deterministic and clear, so that is not desirable.
db.inspections.deleteMany({ "test": 1 })
db.inspections.deleteOne({ "test": 3})
db.inspection.drop()
  • In order to delete a collection, drop operation is used.
  • After any of the delete and drop commands are used, the data is gone for good, so use them wisely.
  • Removing all collections in a database, also removes the database.
╔══════════╦══════════════════════════╗
║ Operator ║ Explanation ║
╠══════════╬══════════════════════════╣
║ $eq ║ Equal to ║
║ $neq ║ Not equal to ║
║ $lt ║ Less than ║
║ $lte ║ Less than or equal to. ║
║ $gt ║ Greater than ║
║ $gte ║ Greater than or equal to ║
╚══════════╩══════════════════════════╝
  • Above operators can be used to query documents in a collection in the following way:
db.trips.find({ "tripduration": { "$lte" : 70 },                         
"usertype". : { "$ne": "Subscriber" } })
.pretty()
  • The logic opeations are used as follows:
╔══════════╦═══════════════════════════════════════════════════╗
║ Operator ║ Use ║
╠══════════╬═══════════════════════════════════════════════════╣
║ $and ║ ║
║ $or ║ { <operator> : [{statement1}, {statement2}, ...]} ║
║ $nor ║ ║
╠══════════╬═══════════════════════════════════════════════════╣
║ $not ║ { $not : {statement}} ║
╚══════════╩═══════════════════════════════════════════════════╝
  • And operator is the default logical operator, explicitly use $and when the same operator is used more than once in the same query.
  • $ sign in the queries not just denotes the use of an operator (like and, or, gt, lt etc.), it also addresses the field value in a document as follows where to find fields that have the same start and destination stations:
db.trips.find({ "$expr": { "$eq": [ 
"$end station id", "$start station id"] } }).count()

Array Operations

{<array_field> : { "$size" : <number>}}
{<array_field> : { "$all" : <array>}}
  • Size operator returns documents which array_field is exactly the given length
  • All operator returns documents whose array_field contains all the elements in the given array in the query

Projection

In order to project a document to a subset of its fields, projections are used as follows:

db.<collection>.find({<query>},{<field1>:1, <field2>:1})
  • The italic part is the projection. In order to add a field to a projection use 1s, exclude a field use 0s. But never mix them! Only time you can mix them is when excluding _id field which is added to the projection by default.
  • You can also project the array fields in a document only to show certain elements in the array as follows which shows the elements of the scores array in the document which has more than 85 score:
db.grades.find({ "class_id": 431 },                
{ "scores": { "$elemMatch": { "score": { "$gt": 85 } } } }).pretty()

--

--

Mehmet Akcay

a geek who loves to understand the reasons behind things... and colors... Colors are cool.