Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB — Ways to get Query Results

Spread the love

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.

Get Results with Asynchronous Iteration

We can get results with async iteration.

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);
    for await (const doc of cursor) {
      console.log(doc);
    }
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We get the data with a query.

Then we can loop through the entries wirh the for-await-of loop to loop through the entries.

Manual Iteration of Results

Also, we can manually iterate through the results.

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);
    while (await cursor.hasNext()) {
      console.log(await cursor.next());
    }
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

to add a while loop that calls the hasNext method that returns a promise that indicates whether there are any results with the resolved value.

Then the cursor.next method returns a promise with the resolved item.

Getting the Results with Stream API

We can pipe the results to a write stream by calling the cursor.pipe method.

For example, we can write:

const { MongoClient } = require('mongodb');
const { Writable } = require('stream');
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);
    cursor.pipe(
      new Writable({
        objectMode: true,
        write(doc, _, callback) {
          console.log(doc);
          callback();
        },
      }),
    );
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We pass an object into the Writable constructor to pipe the items with the write method.

The write method has the doc parameter with the document.

callback is called to indicate that we’re done streaming the result.

Conclusion

There are many ways to get results from the returned results with the MongoDB Node.js client.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *