Add index to Schema

  1. index

    Indexes are special lookup tables that database search engines can use to speed up data retrieval. Without an index, Mongo must perform a collection scan, which means it must scan every document in the collection to select those that match the query.

    In Mongoose, indexes can be defined at the field level or at the schema level.


  1. Using a single index

    A common search request is to retrieve events by event name. In the schema file:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    import { Schema } from '@nestjs/mongoose';

    @Schema()
    export class Event extends mongoose.Document {
    @Props()
    type: string;

    @Props({ index: true }) //Add normal index
    name: string;

    @Props(mongoose.SchemaTypes.Mixed)
    payload: Record<string, any>;
    }

    export const EventSchema = SchemaFactory.createForClass(Event);

  1. Compound Index

    A single index references multiple properties. Multiple properties need to be added to EventSchema.index({}).

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import { Schema } from '@nestjs/mongoose';

    @Schema()
    export class Event extends mongoose.Document {
    @Props()
    type: string;

    @Props({ index: true }) //Add normal index
    name: string;

    @Props(mongoose.SchemaTypes.Mixed)
    payload: Record<string, any>;
    }

    export const EventSchema = SchemaFactory.createForClass(Event);
    EventSchema.index({ name: 1, type: -1});

    Where 1 represents ascending order, -1 represents descending order, the same as sort() in mongoose.


Share