The Web Developer Bootcamp 2024

Colt Steele

Back to MongoDB Index Page


 

MongoDB
other operators
More Operators

Ok, so we've seen how we can Update or Delete documents in our Collections by using specific findCriteria, such as:

  • name: "Chico"
  • age: 10
  • catFriendly: true

I've update our database and added a couple of new fields to our dogs.documents. I've added "size: L" (could be L/M/S), and I've changed our "catFriendly" to be a nested object, so if we look at the updated object, it looks like this:

  • _id: ObjectId('67f976d154c097b94fc8fcc6'),
  • name: 'Chico',
  • age: 10,
  • breed: 'Pit Bull',
  • size: 'L',
  • personality: { catFriendly: true, childFriendly: true }

For starters, what if we wanted to find all dogs that are "catFriendly"? If we notice, catFriendly is now part of a "nested" personality object. Well, in the MongoDB Shell, the syntax for that would be:

  • db.dogs.find ( { 'personality.catFriendly': true } )
In Mongo Compass, you would simply put "{ 'personality.catFriendly': true }" into the search box and press Find.

But want if we want to find say, all dogs that are older, or younger than 5?

Well, we can find more information on Query Operators on the MongoDB Docs website, where it shows a host of different operators for greater than, less than and many more. When you look at the website you notice that these operators are all categorized for us which makes it easier to find operators. You should also notice that all of the operators start with $.

So to answer our question, if we want to find all dogs that are greater then 5, we would use the $gt operator. In the MongoDB Shell it would look like:

  • db.dogs.find ( { age: { $gt: 5 } } )
notice that $gt: 5 is enclosed inside curly braces as an object. Also notice the : (colon) after the "is greater than ($gt)" designation.

In MongoDB Compass, just enter {age: {$gt: 5}} into the search field and press Find.

So Mongo has all sorts of useful operators to modify your searches such as greater than, greater than or equal to, less than, less than or equal to, etc.. Just go to the Query Operators Docs and find the one you need.


Back to Top