Blog>
Snippets

Partial Filter Expressions for Indexes

Create a partial index in MongoDB to only include documents that match a certain filter, optimizing queries for RAG status checks where certain conditions are frequently queried.
const mongoose = require('mongoose');

const ragStatusSchema = new mongoose.Schema({
  status: String,
  lastUpdated: Date
});

// Define the partial index with filter
ragStatusSchema.index({ status: 1 }, { partialFilterExpression: { status: 'critical' } });

mongoose.model('RagStatus', ragStatusSchema);
This piece of code sets up a Mongoose schema for a RAG (Red, Amber, Green) status collection in MongoDB and then applies a partial index on the 'status' field. The partial index only includes documents where the 'status' field is 'critical'. This optimizes queries when checking for documents with a critical status.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Partial Index Filter Test</title>
</head>
<body>

    <!-- A form for interacting with RAG status data -->
    <form id="ragStatusForm">
        <label for="statusInput">Update RAG Status:</label>
        <input type="text" id="statusInput" name="status">
        <button type="submit">Submit</button>
    </form>

<script src="/path/to/mongoose.js"></script>
</body>
</html>
This HTML markup creates a simple form that could be used to update the RAG status in the database. A hypothetical JavaScript source file called mongoose.js is referenced where our partial index code could reside and handle the form submission.
body {
    font-family: Arial, sans-serif;
}

#ragStatusForm {
    margin: 20px;
}

label, input, button {
    margin: 5px 0;
}
This CSS snippet styles the form in the HTML document, providing a font and spacing to make the form easy to read and interact with.