DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Originally published at thewebdev.info

Node.js Basics — MongoDB Index Types

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.

Index Types

MongoDB has different text types.

We can add single field indexes to improve performance for queries that specify ascending or descending sort order on a single field of a document.

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 db = client.db("test");
    const testCollection = await db.collection('test');
    await testCollection.dropIndexes();
    const indexResult = await testCollection.createIndex({ name: 1 });
    console.log(indexResult)
    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 sort = { name: 1 };
    const cursor = testCollection
      .find(query)
      .sort(sort);
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);
Enter fullscreen mode Exit fullscreen mode

We call the sort method with the object with the sort order.

Compound index ae indexes that improve performance for queries that specify ascending or descending sort order for multiple fields in a document.

For example, we can add a compound for the name and rating fields and use it by writing:

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

async function run() {
  try {
    await client.connect();
    const db = client.db("test");
    const testCollection = await db.collection('test');
    await testCollection.dropIndexes();
    const indexResult = await testCollection.createIndex({ name: 1, rating: 1 });
    console.log(indexResult)
    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 sort = { name: 1, rating: 1 };
    const cursor = testCollection
      .find(query)
      .sort(sort);
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);
Enter fullscreen mode Exit fullscreen mode

We have:

const indexResult = await testCollection.createIndex({ name: 1, rating: 1 });
Enter fullscreen mode Exit fullscreen mode

to add the compound index.

Then we call sort with an object that has both the name and rating fields.

Multikey indexes are indexes that improve performance on queries that specifies ascending or descending index on fields that has an array value.

For example, we can create a multikey index and use it by writing:

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

async function run() {
  try {
    await client.connect();
    const db = client.db("test");
    const testCollection = await db.collection('test');
    await testCollection.dropIndexes();
    const indexResult = await testCollection.createIndex({ types: 1 });
    console.log(indexResult)
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3, "types": ["granny smith", "mcintosh"] },
      { "_id": 2, "name": "bananas", "qty": 7, "rating": 1, "types": ["chiquita", "del monte"] },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2, "types": [] },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5, "types": [] },
    ]);
    console.log(result)
    const query = { types: "granny smith" };
    const sort = { types: 1 };
    const projection = { types: 1 };
    const cursor = testCollection
      .find(query)
      .sort(sort)
      .project(projection);
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);
Enter fullscreen mode Exit fullscreen mode

We have:

const indexResult = await testCollection.createIndex({ types: 1 });
Enter fullscreen mode Exit fullscreen mode

to create the index on the types field.

Then we can make the query on the types field.

Conclusion

MongoDB has various types of indexes to optimize the performance of various kinds of queries.

Top comments (0)