MongoDB Guide | Modifying Query Results
Tags: mongodb, cloud, database, beginners
Published: 2023-02-04 15:48:36

## MongoDB Guide | Modifying Query Results
by Jacob Pelletier
Contact me for suggestions, comments, or just to say hello at jacob@yankeedo.io! 👋

**Follow me on my journey in learning [MongoDB](https://www.mongodb.com/).** 

I highly recommend checking out [Mongo University](https://learn.mongodb.com/?_ga=2.83089430.1471118752.1675467284-1993933025.1675122350)!

---

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ydseret748igmf5szkya.jpg)

## What will we be covering in this guide
1. Return results of a query in a specified order
2. Limit number of documents 

---

![sorting](https://media2.giphy.com/media/XVJcwIbSdFNs1Ni7N4/giphy.gif?cid=ecf05e470nmhaa9tb19rlnm8xs9rppxfpqxd9bnvl46dixb7&rid=giphy.gif&ct=g)
## Returning results of a query in a specified order and limiting the number of documents returned.

To perform theses tasks, we will take advantage of cursors and cursor methods. 

A Cursor is a pointer to the result set of a query. There are two cursor methods, cursor.sort() and cursor.limit(). db.collection.find() method returns a cursor of documents that match that query. Cursor methods are chained to queries and perform actions on the result set. 

First, connect to our DB and take a look.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fsvyzeprjk2k0hq3gvt4.png)

Woah, thats a lot of results! 
![woah](https://media2.giphy.com/media/MQ4bWOjn8C9tT2dzIb/200.webp?cid=ecf05e470uy07cmae4ty5ppq9uhw6v2057wl3ilbvfoilyt9&rid=200.webp&ct=g)

Sort() specifies the order in which the query returns matching documents. You must apply 
sort() to the cursor before retrieving any documents from the database.

**Note:**

MongoDB does not store documents in a collection in a particular order. When sorting on a field which contains duplicate values, documents containing those values may be returned in any order.

If consistent sort order is desired, include at least one field in your sort that contains unique values. The easiest way to guarantee this is to include the _id field in your sort query.

**Sort results:**
Let's sort by `property_type` and return listing `name` alphabetically.

```
db.listingsAndReviews
.find({property_type:"House"})
.sort({name:1})
```

A value of 1 means to sort in ascending order, while a value of -1 will mean descending order on that property. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x5nrhxg6dulmrbikzg3h.png)

We can add a projection to make the results easier to read.
```
db.listingsAndReviews
.find({property_type:"House"},
{name:1})
.sort({name:1})
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nd8pl7ihraaup7jxotaw.png)

In MongoDB, capitol letters are sorted first, then lowercase letters. 

**Limit results:**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/goooj0xj14xbuhl7rphh.png)

If you wanted return a document on two conditions:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/132y85uhw5xvvyc5k9sk.png)

Let's find a house, apartment or condo in the US, sort results by listing name in ascending order, and limit results to 5.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3dcljulp739wa1ayz32p.png)

```
db.listingsAndReviews
.find({property_type: 
  {$in: ["House", "Apartment", "Condo"]},
  "address.country_code": "US"})
.sort({name:1})
.limit(5)
```
**Note:** The use of dot notation while accessing nested information is required.

Doing Great! Keep it up!
![doing great](https://media2.giphy.com/media/8qrrHSsrK9xpknGVNF/giphy.gif?cid=ecf05e47obfmtlab5o5o0yi4ddutszxsk9i73pgqc42jo56g&rid=giphy.gif&ct=g)

**From MongoDB docs:**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xxloq59w4kn5arw3k7zj.png)
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0twa0almesnsae8rpm3.png)

Notice that these operations must occur in a specific order.  First db.collection.find(), then sort(), then limit(). 

---

![shopping](https://media4.giphy.com/media/89sIi77nGsdnq/200w.webp?cid=ecf05e47fy9o4rn3dmh3qaqlrvu0i6gcn0cqcjwy36jf1gqf&rid=200w.webp&ct=g)

## Choosing what data to return from a query.
Because you rarely want to return EVERYTHING.

This process is called **projection** (did you catch that we used it above?). Limiting which fields are returned may improve application performance. 

The projection from before.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q439uzk98uzaawjuybs6.png)

This is an example of a projection.
```
cd.collection.find(
  {<field1> : <value1>}, 
  {<field2> : <value2>, 
  <field3> : <value3>})
```

Here, we are finding documents that match `<field1> : <value1>`, and specifying the projection on `{<field2> : <value2>, <field3> : <value3>}`. Stop to appreciate the difference between finding a document based on two fields, and this projection. 


![magnifying glass](https://media2.giphy.com/media/3orieUe6ejxSFxYCXe/200.webp?cid=ecf05e47x5e04kwqi4fcya3oloirsqcmyfs2awc4vdoea3ut&rid=200.webp&ct=g)
```
// finding on two fields
db.collection.find(
  {<field1> : <value1>, 
  <field2> : <value2>})

// finding on one field and projecting on another
cd.collection.find(
  {<field1> : <value1>},
  {<field2> : <value2>})
```

The ID field (_id) is always returned by default. If you do not wish to return the ID field, you can include _id to the projection and setting the value to 0. By setting the value to 0, you are telling MongoDB to exclude this field from the results.

```
cd.collection.find(
  {<field1> : <value1>}, 
  {<field2> : <value2>, 
  <field3> : <value3>},
  _id : 0})
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/esirv274cgsg7o2bjdlf.png)

**Inclusion and exclusion statements cannot be combined!**

You can choose to include fields or include fields, but not both. 

The only exception to this rule is the _id field, which may be included with inclusion statements.

```
db.listingsAndReviews
.find({"property_type": 
  {$in: ["House", "Apartment", "Condo"]},
  "address.country_code": "US"},
  {"name":1, "property_type":1, "address.country_code":1, "_id":0})
.sort({name:1})
.limit(5)
```

**From MongoDB docs:**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lg63circezbr6x60che.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/js5y3i8inoosfxhcya54.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hp2m1mkqmzpz6ut19qfd.png)

**Can you guess what this query does?
**```
db.sales.find({ "customer.age": { $lt: 30 }, 
  "customer.satisfaction": { $gt: 3 }, 
}, 
{ "customer.satisfaction": 1, 
  "customer.age": 1, 
  "storeLocation": 1, 
  "saleDate": 1, 
  "_id": 0, }
);
```

**What about this code?
**
```
db.sales.find({ storeLocation: { 
  $in: ["Seattle", "New York"] }, 
}, { 
  couponUsed: 0, 
  purchaseMethod: 0, 
  customer: 0, 
})
```
---

![counting](https://media3.giphy.com/media/l0XtbC8EniiuwAEOQn/200w.webp?cid=ecf05e47h9rt8txktx33pcaalvv3p26il4tmuwou6xs0usow&rid=200w.webp&ct=g)

## Counting documents in a collection

**What method allows you to count documents?**
`db.collection.countDocuments(<query>, <options>`

The total number of documents in our listingsAndReviews collection.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezixl536y4setkv43jqo.png)

The total number of listing with greater than 5 beds.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/56r4nmi4iy3x3s5mjp0g.png)

```
db.listingsAndReviews
.countDocuments({"beds":{ $gt: 5 }})
```

**From MongoDB docs:**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dmyjajphytuowd2h3aps.png)

**Can you guess what this code does?**
```
db.sales.countDocuments({ 
  items: { 
    $elemMatch: { 
      name: "laptop", 
      price: { $lt: 600 } 
    } 
   } 
})
```

---

## Resources From Mongo University

Use the following resources to learn more about modifying query results in MongoDB:

**Lesson 01:** Sorting and Limiting Query Results in MongoDB
MongoDB Docs: [cursor.sort(](https://www.mongodb.com/docs/manual/reference/method/cursor.sort/?_ga=2.14948278.1471118752.1675467284-1993933025.1675122350))

MongoDB Docs: [cursor.limit()](https://www.mongodb.com/docs/manual/reference/method/cursor.limit/?_ga=2.14948278.1471118752.1675467284-1993933025.1675122350)

**Lesson 02:** [Returning Specific Data from a Query in MongoDB](https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results/?_ga=2.82452374.1471118752.1675467284-1993933025.1675122350)
MongoDB Docs: [Project Fields to Return from Query](https://www.mongodb.com/docs/manual/reference/limits/?&_ga=2.82452374.1471118752.1675467284-1993933025.1675122350#mongodb-limit-Projection-Restrictions)

MongoDB Docs: Projection Restrictions

**Lesson 03:** Counting Documents in a MongoDB Collection
MongoDB Docs: [db.collection.countDocuments()](https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/?_ga=2.82452374.1471118752.1675467284-1993933025.1675122350)


---

![bye](https://media1.giphy.com/media/m9eG1qVjvN56H0MXt8/giphy.gif?cid=ecf05e47dime14zgvfycw5kfbmgfq67hnpay8q09wisbbxu3&rid=giphy.gif&ct=g)

See you in the next guide!
Next guide will be posted soon!