Indexing and aggregation

Indexing causes MongoDB to create a list of values from a chosen field. Indexed fields accelerate query speeds because a smaller set of data can be used to cross-reference and pull from a larger set. We can apply an index to the author field and see performance benefits, especially as our data grows. Additionally, MongoDB has various commands that allow us to aggregate our data. We can group, count, and return distinct values.

Let's create and output a list of authors found in our database.

We'll create a file in the same mongo-app folder, called author.js:

const {MongoClient} = require('mongodb') 
const client = new MongoClient()

client.connect('mongodb://localhost:27018/quotes', ready)

function ready (err, db) {
if (err) throw err
const collection = db.collection('quotes')
collection.ensureIndex('author', (err) => {
if (err) throw err
collection.distinct('author', (err, result) => {
if (err) throw err
console.log(result.join(' '));
db.close()
})
})
}

As usual, we opened up a connection to our quotes database, grabbing our quotes collection. Using collection.ensureIndex creates an index only if one doesn't already exist.

Inside the callback, we invoke the collection.distinct method, passing in author. The resulting parameter in our callback function is an array that we join (using the join method) to a newline delimited string and output the result to the terminal.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset