NoSQL: Retrieving Data from a MongoDB Database

In the latest part of this MongoDB articles’ series, we have explored what are the fundamentals of testing an application using Mongo in combination with Mocha. Today, we are going to learn how to retrieve data from a database and later, we will test if our query went well using Mocha. This is the typical pattern you will follow when developing an application using Mongo: 

  • Idea or concept about the feature you want to implement, how this feature will be composed and what parts of the feature will interact with the database
  • Writing the code that interacts with the database.
  • Writing tests using Mocha to test that everything went well.

Reading data from the database

The first type of queries we are going to explore are reading queries. These are necessary queries that you will write whenever you will want to retrieve some data from your database. Since I’m gonna create a showcase of the various different queries you can write, my advice for you is to create a playground folder with a playground.js file. In this way, you will be able to execute and play around with the code without corrupting the rest of your project.

A query for every goal

As you may remember from the latest article I’ve written, we should now have a single document into our database representing a student called Mark. We will play around with that, but first, let’s copy its id in order to have a unique way to identify it.

  • Go to RoboMongo (Windows user be sure to have your database running in order to correctly work with RoboMongo)
  • Go to the students_tests database and select the collection submenu
  • Select the document that you see on the right panel
  • Right click “View Document”
  • Copy the id of this document into a variable called id inside of our playground.js file

Now let’s explore the different solutions we can use

find queries mongodb

Before analyzing this step by step. I would like to point out to a couple of things. First, for constancy purposes, I have decided to use the _id property for each query and second, this id has been copied from the database as explained earlier. Don’t try to copy this id since its unique for my data and it won’t reflect the data that are sitting inside of your localhost database. Also, notice how like for other operations used in previous articles, the Student model provides us with useful operations for performing queries on our database.

The find() method

The find() method works by passing in as an argument an object with some criteria. This criterion is basically the property that we want to search for. So since here, we want to find a Student with a specific id, we can express this criterion inside of the curly braces {}. We use the find() method when we want to find all the documents that match a given criterion. Please notice how another criterion that we may have used could have been:

find function with parameter

Or we could even have used both of these conditions since multiple criteria are allowed!

find with multiple parameters

The findOne method

Another method we can use is the findOne() method. This method works exactly like the find method except for one big difference. In fact, this method only returns the first document that matches the criteria specified. This means that if we wrote a query to find the user called “Mark” using the findOne() method, even if we had thousands of Mark users in our database we would only get the first one that matches the condition. This can be quite useful in situations where you don’t want to return too many data and slow down your operations.

The findById method

This method explains itself quite well just by reading the name. In this case, we only use one criterion: the id of the document we want to fetch. Since every document has a unique id, also this method will return a record.

Putting it all together

To make these query examples clearer to you, I have prepared a simple series of tests that you can write into your playground.js file and execute it to see what happens:

retrieving data code mongodb

Up to this point, nothing should be new to you and you should be able to fully comprehend anything. Here we are first using the beforeEach() function explained here to ensure that we will have some data inside of our database, then we are retrieving those data from it using the different methods explained earlier. Each of these tests will pass as we haven’t placed any assertion in our code, but the important part is to correctly analyze the output of the console logs and notice how the different results change.

Here is the code for your easy replication and to save you typing it all out

const Student = require('../src/student'); 
const assert = require('assert'); 

beforeEach((done) => {
    const mathStudent = new Student({name : "bill"}); 
    const literatureStudent = new Student({name : "mark"}); 
    const chemStudent = new Student({name : "bill"}); (); (); ();

describe('Finding students using MongoDB', () => {
    it('should find every student called bill', (done) => {
        Student.find({name : "bill"}).then((students) => {

    it('should find the first student called bill', (done) => {
        Student.findOne({name : "bill"}).then((student) => {

    it('should find the student called mark by its id', (done) => {
       Student.findById("5bfadafb407b2f29a4dccf7f").then((student) => {

Bonus section: Automating tests using Nodemon

As you may have already noticed at this point, testing our applications can be quite a boring process due to having to restart our program each time we make a change to our code. Well, this behavior can be bypassed by using a very useful tool called: Nodemon.

To make full use of this tool, we need to modify some of our options inside the package.json file of our project. Type this code into your test section(be sure to have nodemon install in your project):
include scripts example

Let’s explain this update we made to our app in detail:

  • Instead of using mocha—watch we decided to use nodemon. This is somehow necessary since this command can cause problems when working together with mongoose.
  • Inside of our test section inside the package.json file, we have replaced the old command with this new one. Basically, we are telling nodemon to execute the command “mocha -R min” whenever we make some changes to our files. 
  • -R min are basically options telling mocha how to properly format its output to make it clearer to the user

Now, if you run the “npm run test” command inside of your project folder from the terminal, you will be able to see nodemon starting. Whenever you will make a change from now on you will see nodemon automatically restarting your tests. In this way, you will only have to run the testing command once and stop worrying about having to restart everything on every change you make.


In this section, you have learned how to perform basic queries for retrieving data from a MongoDB database. In the next articles, we are going to learn how to perform other types of query and see them in action.

As always, keep in touch with me on twitter @BorrelliDev or check out my blog

Leave a Reply