Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Index Types

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);

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);

We have:

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

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);

We have:

const indexResult = await testCollection.createIndex({ types: 1 });

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.

Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Indexes

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.

Creating Indexes

We can create indexes in our collection to let us enable searches in the collection.

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');
    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)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call the createIndex method on the testCollection to add an index to it.

Then we can query the collection 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');
    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 = { name: "apples" };
    const sort = { name: 1 };
    const projection = { name: 1 };
    const cursor = testCollection
      .find(query)
      .sort(sort)
      .project(projection);
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We can create a text index by setting the value of the key to index to 'text' when we call createIndex .

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: 'text' });
    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 = { $text: { $search: "apples" } };
    const projection = { name: 1 };
    const cursor = testCollection
      .find(query)
      .project(projection);
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We have:

const indexResult = await testCollection.createIndex({ name: 'text' });

to add a text index to the name field.

Then we can write:

const query = { $text: { $search: "apples" } };

to make a text search query and return the result from it.

Conclusion

We can add index to a MongoDB collection with the createIndex method.

To enable text searches, we can add text indexes.

Categories
MongoDB Node.js Basics

Node.js Basics — Skipping and Limiting MongoDB Results

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.

Limit the Number of Returned Results

We can limit the number of returned results by calling the limit 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');
    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 = { length: -1 };
    const limit = 3;
    const cursor = testCollection.find(query).sort(sort).limit(limit);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call the limit method with the limit to set the max number of results to 3.

Also, we can set the properties in the query object.

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');
    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 }, limit: 3
    }
    const cursor = testCollection.find(query, options);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We put the limit property in the options object instead of calling limit to limit the number of results.

We can call the skip method to skip the first number of 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');
    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 = { length: 1 };
    const limit = 3;
    const skip = 3;
    const cursor = testCollection.find(query).sort(sort).limit(limit).skip(skip);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We use the skip method with the limit method to add pagination for the results.

We skip the amount of results to reach the given page.

And limit sets the max number of results per page.

Conclusion

We can limit the number of results and skip some results with the MongoDB Node.js client.

Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Cursor and Sorting

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);

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);

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);

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);

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.

Categories
MongoDB Node.js Basics

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

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.