Date fields or Object of date fields

Am converting a project from Mysql to MongoDb and a table has about 6 date fields like so:

            created_at: Date;
            updated_at: Date;
            published_at: Date;
            released_at: Date;
            cropped_at: Date;
            optimized_at: Date;

Would it be a bad idea to store them in an object field e.g. { dates: {....dates}}?
Is there any performance downside to this when querying the dates?

If you are planning a model refactoring, I am suggesting that you look at Building with Patterns: The Attribute Pattern | MongoDB Blog.

It might look like:

  dates : 
      action :  [ "created" | "updated" | ... | "optimized" ]
      date : Date

I single composite index could served all action/date queries. Having different field names, force you to have multiple index. Having less index serving more queries often ends up being more performant because the working set is potentially smaller. It would also be easy to add a new action (example: “retired” or “deleted”) because it is a new value rather than a new field name.

However, if date queries are not part of the normal use case, it might be better to have them in a different collections. It is hard to tell without the use cases.

1 Like

@steevej Thank you for your response. I have gone through the suggested blog post and it suggests saving them in an array just like your reply suggested also.

But why array and not key-value object?
For example

 dates: {
   created: Date,
   updated: Date;
   published: Date;
   released: Date;
   cropped: Date;
   optimized: Date;

One of the key argument from the blog is

Indexing becomes much more manageable by creating one index on the elements in the array:

which is in line with


By the last sentence, I mean that you do not need to modify your schema for the new action.
More importantly you do not need to add a new index to support query that uses the new value.

1 Like

Okay i understand now… Array makes it easy to index…

So i can index dates.action instead of dates.whateverDate. :grin:

Thank you.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.