1

I'm working through an example that uses mongoose to populate a MongoDB.

var eventSchema = new mongoose.Schema({
    _id: { type: String },
    name: { type: String, required: true},
    description: {type: String},
    venue: {type: String},   });   
eventSchema.plugin(require('./plugins/pagedFind'));
eventSchema.index({ name: 1 });
eventSchema.index({ date: 1 });
eventSchema.index({ venue: 1 });

I didn't know what schema.index was; so I looked it up; http://mongoosejs.com/docs/guide.html; What I've learned is that it is a way to sort your collection besides the default _id sorting.

But is there any difference between what I've written and the following?

eventSchema.index({ name: 1, date: 1,venue: 1  });
pivu0
  • 138
  • 1
  • 10
  • Possible duplicate of [Creating Multifield Indexes in Mongoose / MongoDB](https://stackoverflow.com/questions/12573753/creating-multifield-indexes-in-mongoose-mongodb) – RIYAJ KHAN Jun 14 '17 at 17:17
  • I know that already, I want to know the difference between the two ways – pivu0 Jun 14 '17 at 17:18

1 Answers1

5

The difference is 2, as in 2 indexes.

This creates 3 separate indexes:

eventSchema.index({ name: 1 });
eventSchema.index({ date: 1 });
eventSchema.index({ venue: 1 });

This creates 1 compound index:

eventSchema.index({ name: 1, date: 1, venue: 1  });

With earlier versions of MongoDB, compound indexes were the only way to create indexes for queries that matches multiple fields.

However, starting with version 2.6, MongoDB can combine multiple single-field indexes for a single query, which reduces the need to use compound indexes (which require some careful planning about which queries and sorting will be performed).

More info:

robertklep
  • 198,204
  • 35
  • 394
  • 381