Indexing Design Fundamentals / Creating Indexes

Create Indexes

Below is the code used to create multiple indexes with different properties. The createIndexes database command can also be used to create a single index.


Code

Create Indexes


Use the createIndexes database command to create one or multiple indexes with different properties. The indexes that we will create with this command are in the indexes array.

We create the first compound index on fields userId, timestamp, and category and store the values in ascending order. The name of this index is userId_timestamp_category_index.

The second index is a partial index on the userId and isRead<partialFilterExpression specifies that only isRead fields with the value false should be included in the index. The name of this index is isRead_userId_partial_index.


db.runCommand({
  createIndexes: "messages",
  indexes: [
    { key: { userId: 1, timestamp: 1, category: 1 }, name: "userId_timestamp_category_index" },
    { key: { isRead: 1, userId: 1 }, partialFilterExpression: { isRead: false }, name: "isRead_userId_partial_index" }
  ]
});