Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose indexes at both field and schema levels

I understand that indexing can be a valuable tool for quickly retrieving data, if implemented properly. I would like to be able to scan my documents for a certain field value or a combination of field values.

There are two fields I would be indexing (category, tags). Category is a string and tags is an array. I need to be able to query for items in a specific category and/or items that contain a specific tag.

Here are three examples:

  1. Show me all of the documents in the category: "cars"
  2. Show me all of the documents that contain the tag: "electric"
  3. Show me all of the documents in the "cars" category that contain the "electric" tag

Will a schema level index for both fields suffice for all three scenarios?

docSchema.index({category:1, tags:1});

Or do I also need to define them at the field level, to support the scenarios when I am only searching through a single field?

docSchema = mongoose.Schema({
    category: {
        type: String,
        index: true
    },
    tags: {
        type: [String],
        index: true
    }
});
like image 918
George Hess Avatar asked Oct 23 '25 17:10

George Hess


1 Answers

docSchema.index({category:1, tags:1}); is a compound index.

This compound index supports the scenarios 1 and 3:

-> Show me all of the documents in the category: "cars"

-> Show me all of the documents in the "cars" category that contain the "electric" tag

To support scenario 2 you will need to define an additional single index on the tag field. docSchema.index({tags:1});

A compound index supports queries that involve all fields in the compound index as well as queries that involve a prefix of the compound index. In this case your compound index supports queries involving both categories and tags as well as queries involving just categories.

To better understand the logic please take a look at the Compound Indexes articles on MongoDB documentation site. Pay special attention to the section that talks about Prefixes.

like image 156
Leonel Machava Avatar answered Oct 26 '25 09:10

Leonel Machava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!