Blog>
Snippets

Index Creation for Optimized Queries

Show how to create efficient indexes in MongoDB for common query patterns in a RAG (Red, Amber, Green) status data model to speed up read operations.
// Connect to the MongoDB client
const MongoClient = require('mongodb').MongoClient;
const uri = 'your-mongodb-uri';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

// Database and collection
const dbName = 'yourDatabaseName';
const collectionName = 'ragStatusData';

client.connect(err => {
  if (err) throw err;
  const db = client.db(dbName);
  const collection = db.collection(collectionName);

  // Create an index for the 'status' field
  collection.createIndex({ 'status': 1 }, { background: true }, (indexErr, result) => {
    if (indexErr) throw indexErr;
    console.log(`Index created: ${result}`);
    client.close();
  });
});
The JavaScript code snippet connects to a MongoDB database instance and creates an ascending index on the 'status' field of the 'ragStatusData' collection to optimize queries filtering by status, which is common in a Red, Amber, Green (RAG) status data model. The index is created in the background for minimal impact on the database's performance.