DEV Community

loading...

Node.js Basics — MongoDB Cursor and Sorting

aumayeung profile image John Au-Yeung Originally published at thewebdev.info ・3 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.

Closing the Cursor

To clean up any resources used after getting the results from a collection, we call the cursor.close method.

To do that, we 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",
    };
    const cursor = testCollection.find(query);
    const queryResult = await cursor.toArray();
    console.log(queryResult);
    await cursor.close();
  } finally {
    await client.close();
  }
}
run().catch(console.dir);
Enter fullscreen mode Exit fullscreen mode

We call cursor.close after we’re done using the cursor.

Sort Results

The MongoDB client lets us sort the results we retrieve.

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 = {};
    const sort = { rating: -1 };
    const cursor = testCollection.find(query).sort(sort);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);
Enter fullscreen mode Exit fullscreen mode

We sort the results by the rating property in descending order.

-1 means we’re sorting by descending order.

Also, we can sort by multiple fields. 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 = {};
    const sort = { rating: 1, qty: 1 };
    const cursor = testCollection.find(query).sort(sort);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);
Enter fullscreen mode Exit fullscreen mode

Skip Returned Results

We can skip returned results. To do that, we call the find method a collection object with the 2nd argument that has the skip property.

To do that, we 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');
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const query = {};
    const options = {
      sort: { rating: -1 },
      skip: 2,
    };
    const cursor = testCollection.find(query, options);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);
Enter fullscreen mode Exit fullscreen mode

The options object has the sort property to sort the items by the rating property in descending order.

The skip property is set to the number of items to skip.

Conclusion

We can sort and skip results from with the cursor object.

Also, we should close the cursor when we’re done working with it.

Discussion (0)

pic
Editor guide