02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Finding complicated things with operators

Finding Complicated Documents Using Operators in MongoDB

In this tutorial, we will explore how to find documents within a MongoDB collection using more advanced filtering techniques. The methods covered in this lesson will help you perform more precise searches using MongoDB operators.

Introduction

In the previous tutorial, we learned how to add documents to a MongoDB collection and how to find them using basic search methods like simple filters and limit functions. In this tutorial, we will take it a step further by using more sophisticated MongoDB operators to find exactly what we need from our collections. This approach will give us the ability to perform complex searches.

MongoDB has built-in operators that allow us to construct highly specific queries. These operators, which usually start with the $ symbol, make it easier to refine your searches and filter documents according to precise conditions. Let’s dive into this by looking at practical examples of how these operators work.

Prerequisites

Before proceeding, make sure your MongoDB server is up and running, and that you have a collection ready for searching.

Finding Specific Documents

To start off, let’s get back into our MongoSample database and access the users collection.

use MongoSample;

Now that we're in the right database, we can start searching for specific users.

Using the find() Method

The find() method in MongoDB is essential when you want to locate documents in a collection. You can also use findOne() if you want to return only one document that matches a condition. For example:

db.users.findOne();

The command above will return the first document found within the users collection.

Note: findOne() is equivalent to using find() with the limit(1) function, though findOne() provides a neater output.

Searching with Multiple Criteria

To perform more advanced searches, you can specify multiple search criteria. For example, let’s say you have two users named "Hen," and you want to search for all users named "Hen":

db.users.find({ name: "Hen" });

The above command will return all users with the name "Hen." In cases where a user may appear multiple times, it's important to understand that the name property is not a unique identifier. MongoDB will automatically assign unique IDs (_id) to each document when they are created.

Finding with the $in Operator

To find documents that match any value within an array of possible values, you can use the $in operator. For example, let’s find users named "Hen" or "Ben":

db.users.find({ name: { $in: ["Hen", "Ben"] } });

The $in operator is useful for situations where you need to find documents with specific properties among multiple options.

Using Logical Operators

Sometimes you may need to search for documents based on more complex logic. One such scenario would be finding users with either specific names or meeting another condition, such as age.

The $or Operator

If you want to search for users whose name is "Ben" or who are over 50 years old, you can use the $or operator.

db.users.find({
  $or: [
    { name: "Ben" },
    { age: { $gt: 50 } }
  ]
});

In the example above, we use the $or operator to find documents that match either condition: users named "Ben" or users older than 50. The $gt (greater than) operator is used here to filter users based on age.

Note: Always ensure you properly close your brackets and parentheses when using multiple conditions. Errors like missing brackets can cause the query to fail.

Debugging Common Errors

While using these advanced operators, you may run into issues such as incorrect syntax or unclosed brackets. If you notice the terminal not executing a command correctly, it’s most likely expecting more input due to a missing closing bracket.

To exit from incomplete statements, you can press Ctrl + C to return to the Mongo shell.

Practical Application

When working with large databases, you may want to paginate your results rather than return every document that matches a condition. To limit the number of returned documents and skip others, use limit() and skip() methods. For instance:

db.users.find().limit(2).skip(1);

The command above will return two documents while skipping the first one in the results. This type of query is useful for creating pagination systems for web applications.

Summary

In this tutorial, we learned how to enhance our search capabilities using MongoDB operators like $in, $or, and $gt. These operators allow us to create more sophisticated and precise queries when searching through collections.

In the next lesson, we will look at how to remove documents, collections, and entire databases in MongoDB. Deleting data is just as important as adding or finding it, especially when dealing with data maintenance or cleanup tasks.

Important Update (2023): Starting from MongoDB 4.2, the aggregation framework has become more powerful and flexible, and certain features have been optimized. Consider using the aggregation pipeline for more complex searches as it can perform sophisticated transformations and filters directly within MongoDB.

Video Transcript

00:01While in the last lecture we took a look at finding
00:04things, simply using limitations, using simple filters.
00:08In this lecture we're gonna go ahead
00:10and take it a step further as we add advanced filtering
00:14that enables us, enable us to find things more specifically,
00:17more accurately using special behaviors
00:20that are available built into MongoDB.
00:24So let's go ahead and take a look at these behaviors
00:26and operators that will take advantage
00:29to create more complex search terms.
00:33Alright, welcome back
00:34and uh, we're back in our Mongo sample database
00:37and we're continuing to look at find,
00:39because it's obviously the most important thing.
00:41It's gonna help you find the different elements
00:43that you're stashing in your database.
00:45So what I wanna show you next is I'm just gonna go into my
00:48database into users and we've created their three users.
00:51We've created Ben, be
00:52and hen What I want to do is I want to find,
00:54but I don't wanna find everyone,
00:56nor do I wanna find someone specific.
00:58As we saw that, we would just put that underscore ID
01:01and then set the idea as we've seen it earlier,
01:04as the value that we got back from.
01:06And by the way, if we do find one
01:07just to get, we'll just get one.
01:09And by the way, we could put your uh uh, a qualifier or not.
01:13And by the way, if I'm already saying this,
01:14find one is equivalent to find
01:17and then limit one that's basically the same thing.
01:21And that will basically return to us the same thing.
01:24Only this time or only the find one is make
01:26showing it in a clean way.
01:27But this is the exact same hen. Okay?
01:29So, but let's go back to our find.
01:31And in our find, what I really want to do is I want,
01:33and everything that we're saying is really relatable
01:36to find one as well, by the way.
01:38So I'm gonna go back again, I'm into IDB in my users
01:41and I want to find, but I wanna, I want to specify
01:44that I want specifically, I want hen.
01:47Alright, so hen is a string, so I need to send it inside
01:49of a stringy thing, curly bracket,
01:51close round bracket enter.
01:53Beautiful, I got hen now what would happen in a situation
01:57where I want to get or hen,
01:59and by the way there could be five different
02:01hens, no pun intended.
02:03If I put here another insert
02:07and I insert another person
02:09and this person will have a name.
02:11But surprisingly there's another person in the universe
02:14that their name is hen only.
02:15This hen is aged much higher and this one is 80 years old.
02:20And actually they don't even have an email, right?
02:22So this is surprise, surprise.
02:24Um, it's an older person without an email. Very weird stuff.
02:27But it happens. Uh, by the way, this um, hen has children
02:31as well and their children, oops.
02:35And there's no children. They have empty children,
02:38but they have an array with children
02:39that have no children in them.
02:40Let's say. Now if I go back here and I go
02:42and I do another search for hen this time
02:45around, I'm getting two hens.
02:46So this was just to make it more explicit that that,
02:49because I said a name does not
02:51necessarily mean that it's unique.
02:52The only thing unique is really these identifiers
02:55and the IDs right now.
02:56Okay, now let's continue onwards.
02:58So what if I wanted to get or hen
03:02or anyone that's called Ben to do that,
03:04I would go in instead
03:06of assigning directly the value hen I'm gonna open a curly
03:10bracket and close another curly bracket.
03:12And in here I'm gonna type dollar in which by the way,
03:15anytime something starts with a dollar, it's a directive
03:19to MongoDB to do something.
03:21And in this case, what I want
03:22to do is I'm gonna send in an array.
03:24And in this array I'm gonna specify
03:26what are the values that are acceptable.
03:28So hen is acceptable and Ben is acceptable as well.
03:33That's all I really had to do.
03:34And if I just go ahead
03:35and type enter, I'm gonna get all the different
03:38and let me just uh, space things out a bit.
03:40I'm gonna get all the three items,
03:41which will be hen Ben and hen again.
03:44Beautiful. So that is, if that is the, you know,
03:48you would say or Ben or hen,
03:50but really what I'm doing here is, is in inside
03:52of my name I'm saying I want to get this one or that one.
03:55Now you might ask me, okay, so what if you really want a
03:58or condition such as we want anyone that's named Ben
04:02or we want anyone that is over 50, either
04:06or they have to be Ben or over 50.
04:09So let's go ahead and create that type of logic.
04:11So I'm gonna go to my DB again
04:13and users find I'm gonna open a curly bracket,
04:17but this time around because I want to create here an
04:19or I'm just gonna start with a dollar
04:21or which will basically tell MongoDB
04:25that what's happening now
04:26what I'm gonna be sending you right now is an or is an
04:30or now with the or I'm gonna send inside an array as well.
04:34And each array is gonna contain an object.
04:37So I have your object one, I'm pre creating those objects.
04:40I have two objects that I wanna send.
04:42So what is the first or the first
04:44or is that the name is Ben.
04:46Okay, so we set ourselves names. So you have to be Ben.
04:49Our second qualifier is if you're over 50 now
04:53to create over 50, I'm gonna use another, um, another rule,
04:57another directive to MongoDB.
05:00And I'm gonna say dollar greater than,
05:02and I'm gonna set here 50.
05:07Now by the way, I forgot
05:08because it's not only greater than what is greater than,
05:10we don't know what is greater than we first wanna go ahead
05:13and and define the who do, what do we wanna approach.
05:16So in this case, we wanna approach the
05:18age, approach the age.
05:19And instead of specifying directly a number,
05:21I'm gonna put here an object.
05:23And inside of my object, I'm gonna say here that I want it
05:25to be greater than the value to be greater than 50.
05:29Okay? So apologies for that.
05:31So what happened was I was, I confused myself
05:33and what actually happened is I forgot
05:35to close one of my brackets.
05:37So you could see here that we have your one bracket,
05:39but then we didn't close this one.
05:41So it's basically thinking my execution is not complete
05:44yet thinking that I want
05:45to continue typing here something which I don't.
05:48So I'm gonna go ahead and step out of this
05:50by typing on the C control C.
05:53And what I wanna do is I want to type it over again,
05:55but this time around I wanna
05:56Make sure that I do actually the close it.
06:00So this ca case around, let's just make sure
06:03that everything is closed correctly and here we go.
06:07This looks a little bit better. Does it?
06:09I'm not sure I,
06:13yeah, yeah, yeah.
06:16There we go. Alright,
06:17so I just forgot there one closing bracket therein.
06:20Because of that, things didn't work
06:22and in this case you could see
06:23that we're getting back anyone that has called Ben
06:26or anyone that their age is greater than 50.
06:29Now you don't have to memorize this.
06:30And I added into the documentation a link
06:34to all the different types of, uh,
06:35of options you have there.
06:37And I do encourage you to check them out,
06:38get familiar with them.
06:40'cause you're definitely gonna need them at some point in a
06:42real world project as well.
06:44In this lecture, we really wrapped up the different types
06:47of ways you could use find to find different elements
06:51to find more accurately different
06:53documents within collections in the next election.
06:56We're gonna continue a step further
06:58as we're gonna take a look at how do we actually delete
07:01documents, collections, and databases.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!