Introduction to MongoDB — Operators

Waqas Ahmad
5 min readSep 21, 2023

--

Getting Set Up

Please read the first guide in this series for more information about setting up MongoDB — Installation, Shell, and Database Management.

Operators

There are four major types of Operators in MongoDB. They are:

  • Query and Projection Operators
    -Query operators provide ways to locate data within the database.
    -Projection operators modify how data is presented.
  • Update Operators
    -Update operators are operators that enable you to modify the data in your database or add additional data.
  • Aggregation Pipeline Operators
    -Aggregation pipeline operations have a collection of operators available to define and manipulate documents in pipeline stages.
  • Query Modifiers
    -Query modifiers determine the way that queries will be executed.

We’ll be looking into just a few operators in this guide. To compare operators, we’ll need more fields in our records. Start by adding a few more records and we’ll delete them later on.

1 > db.students.insert([
2 { name: "Bebo", age: 5 },
3 { name: "Chinna", age: 10 },
4 { name: "Elukaludha", age: 15 },
5 { name: "Kaalejoo", age: 20 },
6 { name: "Vela Thedoo", age: 25 },
7 { name: "Kanna Lammoo", age: 30 },
8 { name: "Daydee", age: 40 },
9 { name: "Paati", age: 55 },
10 { name: "Thathaa", age: 60 }
11]);

Executing the above, command we get the following success message:

1 > db.students.insert([
2... {"name": "Bebo", "age": 5},
3... {"name": "Chinna", "age": 10},
4... {"name": "Elukaludha", "age": 15},
5... {"name": "Kaalejoo", "age": 20},
6... {"name": "Vela Thedoo", "age": 25},
7... {"name": "Kanna Lammoo", "age": 30},
8... {"name": "Daydee", "age": 40},
9... {"name": "Paati", "age": 55},
10... {"name": "Thathaa", "age": 60}
11... ]);
12BulkWriteResult({
13 "writeErrors" : [ ],
14 "writeConcernErrors" : [ ],
15 "nInserted" : 9,
16 "nUpserted" : 0,
17 "nMatched" : 0,
18 "nModified" : 0,
19 "nRemoved" : 0,
20 "upserted" : [ ]
21})
22> db.students.find();
23{ "_id" : ObjectId("593142968e61243307417cd2"), "name" : "Bebo", "age" : 5 }
24{ "_id" : ObjectId("593142968e61243307417cd3"), "name" : "Chinna", "age" : 10 }
25{ "_id" : ObjectId("593142968e61243307417cd4"), "name" : "Elukaludha", "age" : 15 }
26{ "_id" : ObjectId("593142968e61243307417cd5"), "name" : "Kaalejoo", "age" : 20 }
27{ "_id" : ObjectId("593142968e61243307417cd6"), "name" : "Vela Thedoo", "age" : 25 }
28{ "_id" : ObjectId("593142968e61243307417cd7"), "name" : "Kanna Lammoo", "age" : 30 }
29{ "_id" : ObjectId("593142968e61243307417cd8"), "name" : "Daydee", "age" : 40 }
30{ "_id" : ObjectId("593142968e61243307417cd9"), "name" : "Paati", "age" : 55 }
31{ "_id" : ObjectId("593142968e61243307417cda"), "name" : "Thathaa", "age" : 60 }
32>

Note: Intentionally the other records have been hidden in the previous output.

Now we have a number of names with ages. Let’s try to find those who are older than 18. The command and query are as follows:

db.students.find({
2 age: {
3 $gt: 18
4 }
5});

With the above command, we have the list of students who are aged above 18.

> db.students.find({"age": {$gt: 18}});
2{ "_id" : ObjectId("593142968e61243307417cd5"), "name" : "Kaalejoo", "age" : 20 }
3{ "_id" : ObjectId("593142968e61243307417cd6"), "name" : "Vela Thedoo", "age" : 25 }
4{ "_id" : ObjectId("593142968e61243307417cd7"), "name" : "Kanna Lammoo", "age" : 30 }
5{ "_id" : ObjectId("593142968e61243307417cd8"), "name" : "Daydee", "age" : 40 }
6{ "_id" : ObjectId("593142968e61243307417cd9"), "name" : "Paati", "age" : 55 }
7{ "_id" : ObjectId("593142968e61243307417cda"), "name" : "Thathaa", "age" : 60 }
8>

The other similar commands are $gte, $lt, $lte, $eq, $ne, $in, $nin. More information on these can be found here.

Sorting

What’s a database management system without sorting? To sort, we will be using the sort() function on any cursor (the result of find() the operation and similar operations). The sort() function takes one object parameter and it has the field names as keys and the values are either 1 or -1, where they are either ascending or descending. Let's try sorting the students by their names. The command is as follows:

1 > db.students.find().sort({
2 name: 1
3});

And executing the above, we get everything sorted.

1 > db.students.find().sort({
2... "name": 1
3... });
4{ "_id" : ObjectId("593142968e61243307417cd2"), "name" : "Bebo", "age" : 5 }
5{ "_id" : ObjectId("593142968e61243307417cd3"), "name" : "Chinna", "age" : 10 }
6{ "_id" : ObjectId("593142968e61243307417cd8"), "name" : "Daydee", "age" : 40 }
7{ "_id" : ObjectId("593142968e61243307417cd4"), "name" : "Elukaludha", "age" : 15 }
8{ "_id" : ObjectId("593142968e61243307417cd5"), "name" : "Kaalejoo", "age" : 20 }
9{ "_id" : ObjectId("593142968e61243307417cd7"), "name" : "Kanna Lammoo", "age" : 30 }
10{ "_id" : ObjectId("593142968e61243307417cd9"), "name" : "Paati", "age" : 55 }
11{ "_id" : ObjectId("593142968e61243307417cda"), "name" : "Thathaa", "age" : 60 }
12{ "_id" : ObjectId("593142968e61243307417cd6"), "name" : "Vela Thedoo", "age" : 25 }
13>

Let’s sort in descending order too:

> db.students.find().sort({   "name": -1 });
2{ "_id" : ObjectId("593142968e61243307417cd6"), "name" : "Vela Thedoo", "age" : 25 }
3{ "_id" : ObjectId("593142968e61243307417cda"), "name" : "Thathaa", "age" : 60 }
4{ "_id" : ObjectId("593142968e61243307417cd9"), "name" : "Paati", "age" : 55 }
5{ "_id" : ObjectId("593142968e61243307417cd7"), "name" : "Kanna Lammoo", "age" : 30 }
6{ "_id" : ObjectId("593142968e61243307417cd5"), "name" : "Kaalejoo", "age" : 20 }
7{ "_id" : ObjectId("593142968e61243307417cd4"), "name" : "Elukaludha", "age" : 15 }
8{ "_id" : ObjectId("593142968e61243307417cd8"), "name" : "Daydee", "age" : 40 }
9{ "_id" : ObjectId("593142968e61243307417cd3"), "name" : "Chinna", "age" : 10 }
10{ "_id" : ObjectId("593142968e61243307417cd2"), "name" : "Bebo", "age" : 5 }
11>

Blimey! Both work flawlessly.

Limiting Results

With the previous example, we were able to sort students based on age, in either descending or ascending order. If we needed to find the oldest of the group, we’d simply sort them descending based on their age and then limit our result to one student.

Similar to the aggregate functions in traditional RDBs, MongoDB has a function called limit() that can be used on the find() results AKA the cursor.

The limit() the function takes one parameter, which is the integral value of limiting to the number of results given in it. In our case, it is going to be 1.

1 > db.students
2 .find()
3 .sort({
4 age: -1
5 })
6 .limit(1);

Ah, here we go. We get only Thatha as our senior student.

1 > db.students.find().sort({
2... "age": -1
3... }).limit(1);
4{ "_id" : ObjectId("593142968e61243307417cda"), "name" : "Thathaa", "age" : 60 }
5>

Counting Records

There should be a way to count the number of students we have, right? Right. Let’s try the count() cursor. To do that, we have the command:

1 > db.students.find().count();

And wow, we get the nine students:

1 > db.students.find().count();
2 9
3 >

Both limit() and count() should feel very familiar if you've used MySQL (or any RDB).

Iterating Results

We all know that MongoDB is nothing but JavaScript. So, why not use the Array and Object functions on the Database? It’s possible using forEach() the method, which can be applied to find() results.

forEach() takes a function as its only argument. The current document or result or record will be passed to it. Basically, the function has the following syntax:

1 > db.students.find().forEach(function(stud) {
2 print("Student Name: " + stud.name);
3});

We can use the concatenation operator like our regular JavaScript. Executing the above, we get:

1 > db.students.find().forEach(function (stud) {
2... print("Student Name: " + stud.name);
3... });
4 Student Name: Bebo
5 Student Name: Chinna
6 Student Name: Elukaludha
7 Student Name: Kaalejoo
8 Student Name: Vela Thedoo
9 Student Name: Kanna Lammoo
10 Student Name: Daydee
11 Student Name: Paati
12 Student Name: Thathaa
13 >

Clearly, having a JavaScript-like structure makes MongoDB more versatile than RDBs. Whereas MySQL would struggle to perform the task above, MongoDB crushes this problem.

Conclusion

I hope this series of guides have exposed the basics of MongoDB, an increasingly popular NoSQL database that can enhance pretty much any application that relies on using lots of data.

As always, please thumbs up to this guide if you enjoyed it. Thanks for reading!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Waqas Ahmad
Waqas Ahmad

Written by Waqas Ahmad

Software Engineering Leader | Consultant Cloud Infra DBA at Systems Limited

No responses yet

Write a response