Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

How to project an array by its index range?

I saved a calendar as shown in the attached picture.How to project a range of days’ prices based on the days array index? For example, “days” array elements 10-15. Or, should I convert the days array to be objects(dictionaries) for better performance and easier access(query)?

Thank you
Kai

This is the continuation of a thread started at MongoDB University. I recommended to followup in here as it was outside the scope of the MDBU forum. The following was my reply:

You should take a look at $slice athttps://docs.mongodb.com/manual/reference/operator/aggregation/slice/ for this particular issue.

Arrays are potentially more efficient:

1. Arrays have no explicit keys that are stored compared to a dictionary
2. Faster to access an array element compared to a dictionary

I wrote potentially because I have no clue about how it is done in MongoDB.

In your case since the index is the day it is redundant to keep it as part of the array since you already have this information as year: and month: fields.

What is the structure of the price: object? If it is something like { min: x, max: y, avg: z }, it might be more efficient to have 3 arrays of simple values. It might since it is possible that the keys, min:, max: and avg: are not copied in each Object but if they are the 3 arrays of simple values are better.