DEV Community

Cover image for Getting started with Mongoose Querying
JianB
JianB

Posted on

Getting started with Mongoose Querying

In this Article I will go over the Mongoose Model.find() which is the main command to do queries with Mongoose. I hope this Article might help out some beginners like me and get you upto speed faster with Querying. Sit back, read & Enjoy !

Equality Checks

We created a Model for dancer and added 5 dancers to it.

const Dancer = mongoose.model("Dancer", mongoose.Schema({
    name: String,
    age: String,
    style: String
}))

await Dancer.create([
  { name: 'Amy Baxter', age: 22, style: 'Ballroom' },
  { name: 'Billy Clinton', age: 30, style: 'Tap Dance' },
  { name: 'Sara Bibi Clinton', age: 45, style: 'Techno' },
  { name: 'Shakira', age: 45, style: 'Salsa' },
  { name: 'Belle Perez', age: 18, style: 'Salsa' },
]);
Enter fullscreen mode Exit fullscreen mode

Now if we want to find all the dancers whose style is Salsa we need to specify a filter between the brackets of the find. To do that lets add { style: "Salsa" }

const salsaDancers = await Dancer.find({ style: "Salsa" });
// MongoDB may return the result in order
// To sort them we would use the javascript map function like so
salsaDancers.map(dancer => dancer.name).sort() // [36, 45]
Enter fullscreen mode Exit fullscreen mode

You can query for any property this way let's say you wanna do it for name or age instead we would do { name: "Amy Baxter" } or { age: "30" } respectively.

Comparisons

The comparison query operators you will use the most will probably be the $gt and $lt operators and it's variants. Suppose you wanna find all dancers who are younger than 30 you would do:

const dancers = await Dancer.find({ age : { $lt: 30 })
// -> ["Amy Baxter", "Belle Perez"]
Enter fullscreen mode Exit fullscreen mode

Now let's say we want to find all dancers who are 30 or older we can use the $gte operator which means "greater than or equal".

const dancers = await Dancer.find({ age : { $gte: 30 })
// -> ["Amy Baxter", "Sara Bibi", "Shakira"]
Enter fullscreen mode Exit fullscreen mode

Note: the operators $lt, $gt, $lte, and $gte will also work on Strings, dates and other types. Mongoose compares String using the unicode order. If that doesn't work for you you can configure it using collations.

Regular Expression

Now let's say you wanna query dancer with whose names contain Clinton. You can do that in 2 ways with Mongoose.

1 . You can simply query by regular expression as shown below

const dancers = await Dancer.find({ name : /Clinton/ })
// -> ["Billy Clinton", "Sara Bibi Clinton"]
Enter fullscreen mode Exit fullscreen mode

Note: notice the string doesn't contain any "" when working with regular expressions

2 . The other option is using the $regex operator. With this you can pass the regular expression as a String which will be handy if you're getting the query from an HTTP Request.

const dancers = await Dancer.find({ name : { $regex: 'Clinton'} })
// -> ["Billy Clinton", "Sara Bibi Clinton"]
Enter fullscreen mode Exit fullscreen mode

Composition with $and and $or

Normally if you set multiple filter, MongoDB finds documents that match all the filter properties.

const dancers = await Dancer.find(
{ name : { $regex: 'Clinton'},
age : 30
 }) // -> ["Billy Clinton"]
Enter fullscreen mode Exit fullscreen mode

If we want to select all dancers who are either have Clinton in there name or are 30 years of age we can use the $or composition operator.

const dancers = await Dancer.find({
  $or: [
    { age: 30 },
    { name: { $regex: 'Clinton'} }
  ]
});

Enter fullscreen mode Exit fullscreen mode

Or we can also use them together like so :

const dancers = await Dancer.find({
  $and: [
    {
      $or: [
        { age: { $gte: 30 } },
        { style: 'Salsa' }
      ]
    },
    {
      $or: [
        { name: { $lte: 'D' } },
        { name: { $gte: 'B' } }
      ]
    }
  ]
});

Enter fullscreen mode Exit fullscreen mode

This will select all the dancers who are:

  1. Either older than 30 or have a Salsa dancing style
  2. And have a name that starts with a letter before "D" or after "B"

I Hope this small tutorial helped got you a bit up to speed with querying in mongoose. There's lots of other ways to query but these are the most common. If you're looking for more options you can check out this 30 minute youtube video by Web Dev Simplified
to get you all the way to advanced level with querying!

Top comments (0)