Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose sort by child value

I have a parent and child schema that looks like:

schedule = Schema ({
    from: Date,
    to: Date
});

content = Schema ({
    schedule: { type: Schema.ObjectId, ref: "schedule" }
    name: String
});

My question is, how do I query Mongoose to return "all content, sorted by schedule.from date"?

like image 838
Ryan Rife Avatar asked Feb 13 '26 19:02

Ryan Rife


1 Answers

You'll need to sort in two steps on the client, or store the date fields you want to sort on as embedded fields within the content object.

You're trying to do a collection join by using data from two collections. As MongoDB doesn't support a join, you'd need to populate the schedule field and then do a sort locally on the client. If you have very many documents, or want to do paging of data, this of course won't work.

The most efficient means would be to store the date fields in the content model so that you can perform sorting directly from a single document and collection, without the need of a join. While that may cause other issues with the schema design that you'd like to have, you may find this is the most efficient. The benefit of this denormalization process is that you can do sorting, filtering, etc. very easily and efficiently (especially if you've indexed the date fields for example).

schedule = Schema ({
    from: Date,
    to: Date
};

content = Schema ({
    schedule: { type: Schema.ObjectId, ref: "schedule" },
    schedule_data: { 
        from: Date,
        to: Date
    },
    name: String
});

You could leave the schedule field in the content schema if you wanted to be able to quickly locate and update content documents (or if there were other less used or not needed for sorting/filtering).

like image 76
WiredPrairie Avatar answered Feb 16 '26 09:02

WiredPrairie



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!