MongoDB Guide | Modifying Query Results

jacobjpelletier

Jacob Pelletier

Posted on February 4, 2023

MongoDB Guide | Modifying Query Results

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.

I highly recommend checking out Mongo University!


Image description

What will we be covering in this guide

  1. Return results of a query in a specified order
  2. Limit number of documents

sorting

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

Woah, thats a lot of results!
woah

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})
Enter fullscreen mode Exit fullscreen mode

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

Image description

We can add a projection to make the results easier to read.

db.listingsAndReviews
.find({property_type:"House"},
{name:1})
.sort({name:1})
Enter fullscreen mode Exit fullscreen mode

Image description

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

Limit results:

Image description

If you wanted return a document on two conditions:
Image description

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

db.listingsAndReviews
.find({property_type: 
  {$in: ["House", "Apartment", "Condo"]},
  "address.country_code": "US"})
.sort({name:1})
.limit(5)
Enter fullscreen mode Exit fullscreen mode

Note: The use of dot notation while accessing nested information is required.

Doing Great! Keep it up!
doing great

From MongoDB docs:

Image description

Image description

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


shopping

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

This is an example of a projection.

cd.collection.find(
  {<field1> : <value1>}, 
  {<field2> : <value2>, 
  <field3> : <value3>})
Enter fullscreen mode Exit fullscreen mode

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

// 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>})
Enter fullscreen mode Exit fullscreen mode

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})
Enter fullscreen mode Exit fullscreen mode

Image description

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)
Enter fullscreen mode Exit fullscreen mode

From MongoDB docs:

Image description

Image description

Image description

*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, }
);
Enter fullscreen mode Exit fullscreen mode

*What about this code?
*

db.sales.find({ storeLocation: { 
  $in: ["Seattle", "New York"] }, 
}, { 
  couponUsed: 0, 
  purchaseMethod: 0, 
  customer: 0, 
})
Enter fullscreen mode Exit fullscreen mode

counting

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

The total number of listing with greater than 5 beds.
Image description

db.listingsAndReviews
.countDocuments({"beds":{ $gt: 5 }})
Enter fullscreen mode Exit fullscreen mode

From MongoDB docs:
Image description

Can you guess what this code does?

db.sales.countDocuments({ 
  items: { 
    $elemMatch: { 
      name: "laptop", 
      price: { $lt: 600 } 
    } 
   } 
})
Enter fullscreen mode Exit fullscreen mode

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()

MongoDB Docs: cursor.limit()

Lesson 02: Returning Specific Data from a Query in MongoDB
MongoDB Docs: Project Fields to Return from Query

MongoDB Docs: Projection Restrictions

Lesson 03: Counting Documents in a MongoDB Collection
MongoDB Docs: db.collection.countDocuments()


bye

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

💖 💪 🙅 🚩
jacobjpelletier
Jacob Pelletier

Posted on February 4, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

MongoDB Guide | Aggregation
mongodb MongoDB Guide | Aggregation

February 16, 2023