DEV Community

Cover image for 3 useful operators when querying MongoDB
Caleb Hernandez
Caleb Hernandez

Posted on

3 useful operators when querying MongoDB

Hey! I'm Caleb and this is my first post so I hope the information given about this great database will be of much use to you.

We will use the ** Heroes ** collection in this example.

db.heroe.find( { clase: { $in: [ "A", "D" ] } });
Enter fullscreen mode Exit fullscreen mode

In this example we tell it that from the hero collection it looks for the data that is A or D in class, that is, if it does not find data equal to A it will look for those that are equal to D and display them.

The second operator that we will see is $ or, in mongodb you can make queries where you have 2 options, that is, you can find data that meets 2 things or 3 things you are looking for or there is data that compiles with only 1 of the things you are looking for then you can bring them and make your query more complex for example:

db.heroe.find( { $or: [ { clase: "A" }, { nivel: 30} ] } );
Enter fullscreen mode Exit fullscreen mode

In this example we tell you that from the hero collection, look for those whose class is equal to A or whose level is equal to 30, if it does not find one of them, it will show us the one that it did find.

The next that we see is an operator that helps us to make a query a little more detailed and I will show you in the example highlighted below:

db.heroe.find( { clase: "A"},{ nombre: /^p/ } );
Enter fullscreen mode Exit fullscreen mode

As you can see in the example we do the query and we tell it that the hero collection and in class it is equal to A but take a good look at the following, we are telling it that its data begins with py that is operator number 3 of this post, the / ^ / where you can put any letter or number and thus make a more detailed query that can be used for a self-completing type of car or to order your data when displaying them.

Top comments (0)