DEV Community

loading...

Node.js Basics — MongoDB Query and Cursor

aumayeung profile image John Au-Yeung Originally published at thewebdev.info ・2 min read

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Retrieve Data

We can retrieve data by using methods that comes with the MongoDB driver.

The simplest way to get items from a collection is to use the find method.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = {
      name: "Popeye",
      qty: {
        $gte: 90,
        $lt: 110,
      },
    };
    const cursor = testCollection.find(query);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);
Enter fullscreen mode Exit fullscreen mode

We make a query with the qty property to find the documents wirh the qty property greater than or equal to 90 and less than 110.

To find the first document in a collection that meets the condition given in a query, we can use the findOne method with the same argument.

The cursor has the forEach method to let us traverse the query results.

Aggregate

To make a query with a given criteria and then group them together, we can use the $match and $group properties together in a query.

For instance, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = [
      {
        $match: {
          qty: {
            $gte: 90,
            $lt: 110,
          },
        },
      },
      {
        $group: {
          _id: "$status",
          count: {
            $sum: 1,
          },
        },
      },
    ];
    const cursor = testCollection.aggregate(query);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);
Enter fullscreen mode Exit fullscreen mode

In the code above, we get all the entries with the qty property that’s greater than or equal to 90 and less than 110.

Then we group all the items by counting the entries with the $sum operator.

Now we should get the count of the number of items that are found with the query.

Access Data From a Cursor

We can access data from a cursor in different ways.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = {
      name: "Popeye",
      qty: {
        $gte: 90,
        $lt: 110,
      },
    };
    const cursor = testCollection.find(query);
    await cursor.forEach(doc => console.log(doc));
  } finally {
    await client.close();
  }
}
run().catch(console.dir);
Enter fullscreen mode Exit fullscreen mode

query has the query that we want to make.

Then we call forEach on the cursor to loop through each entry.

Conclusion

With the MongoDB Node.js client, there are several ways we can use to retrieve the data we want.

Discussion (0)

pic
Editor guide