0

im building a mongodb app and im just wondering why (even with indexes) my requests getting very slow if documents reach an amount > 1.000.000.

my schema looks like:

const reportSchema = new mongo.Schema({

  organisation: {
    type: mongo.Schema.Types.ObjectId,
    ref: 'Organisation',
    required: true
  },

  reference: {
    type: mongo.Schema.Types.ObjectId,
    required: true
  },

  belongsTo: {
    type: String,
    enum: ['endpoint'],
    required: true
  },

  objects: [{
    property: {
      type: String,
      required: true
    },
    value: {
      type: String,
      required: true
    }
  }]

}, {
  timestamps: true
});

and my index looks like:

reportSchema.index({
  createdAt: -1,
  organisation: 1,
  reference: 1
});

my query:

this.model.find({
          organisation: organisationId,
          reference: referenceId
        })
        .select('_id reference objects createdAt')
        .sort('-createdAt')
        .then(reports => resolve(reports))
        .catch(err => {
          console.error(err);
          reject();
        });

can anybody tell me why? is the index the point of failure? is my query wrong?

Eric
  • 115
  • 1
  • 10
  • I would recommend taking a look at the size of your indexes. If you are using an index that can not fit into RAM you won't be getting the performance boost of using that index. Take a look at this area of the documentation - https://docs.mongodb.com/manual/tutorial/ensure-indexes-fit-ram/ – Lix May 29 '17 at 11:24
  • Use https://docs.mongodb.com/manual/reference/method/cursor.explain/ to check whats happening when you run this query, you can execute the sample query in mongo shell – Atish May 29 '17 at 12:05
  • 3
    I'm pretty sure that index won't be used for that query, since `organisation / reference` (in your query) is not an [index prefix](https://docs.mongodb.com/manual/core/index-compound/#prefixes). As @Astro suggests, use `.explain()` to see if the index is actually being used, but as a quick check, try creating an index `{ organisation : 1, reference : 1 }` and another index `{ createdAt : -1 }` (after removing the index you have now). – robertklep May 29 '17 at 13:53

0 Answers0