Pluralsight Logo
Author avatar

Praveen Kumar

Author badge Author

Introduction to MongoDB - Operators

Praveen Kumar

Author BadgeAuthor
  • Aug 7, 2018
  • 9 Min read
  • 6,208 Views
  • Aug 7, 2018
  • 9 Min read
  • 6,208 Views
SQL
MongoDB
NoSQL

Getting Set Up

Please read the first guide in this series for more information about 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
2
3
4
5
6
7
8
9
10
11
db.students.insert([
  { name: "Bebo", age: 5 },
  { name: "Chinna", age: 10 },
  { name: "Elukaludha", age: 15 },
  { name: "Kaalejoo", age: 20 },
  { name: "Vela Thedoo", age: 25 },
  { name: "Kanna Lammoo", age: 30 },
  { name: "Daydee", age: 40 },
  { name: "Paati", age: 55 },
  { name: "Thathaa", age: 60 }
]);

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

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

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:

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

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

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

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() 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 name. The command is as follows:

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

And executing the above, we get everything sorted.

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

Let's sort in descending order too:

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

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() 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
2
3
4
5
6
db.students
  .find()
  .sort({
    age: -1
  })
  .limit(1);

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

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

Counting Records

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

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

And wow, we get the nine students:

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

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() method, which can be applied on 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
2
3
db.students.find().forEach(function(stud) {
  print("Student Name: " + stud.name);
});

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

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

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 this guide if you enjoyed it. Thanks for reading!

0