I'm struggling to figure out how to retrieve an ordered list from MongoDB data. I need to fetch the results from a Mongo collection using return
and .find()
, structured like this:
For instance, let's say I have one collection for cars with 10 documents:
//document structure:
{
_id: 10,
name: name,
type: [suv, sedan, sport],
driver: [object Driver]
pubDate: new Date()
}
And then, I have another two collections for different types of drivers:
//document structure:
{
_id: 20,
name: name,
type: stupid 'or' clever
}
Now, what I want is to return a list in a specific order, as shown below:
- name: Ford Focus, driver: {name: Nick, type: clever}, pubDate: 20:00;
- name: Nissan GTR, driver: {name: Andrew, type: clever}, pubDate:19:00;
- name: Jaguar xKR, driver: {name: John, type: clever}, pubDate:15:00;
- name: Honda Accord, driver: {name: Petr, type: clever}, pubDate:14:00
- name: Nissan GTR, driver: {name: Andrew, type: clever}, pubDate:13:00;
- name: Tesla, driver: {name: Jorge, type: stupid}, pubDate:20:00;
- name: Audi q7, driver: {name: Peggy, type: stupid}, pubDate:19:00;
- name: BMW 325, driver: {name: Minnie, type: stupid}, pubDate:18:00;
- name: CADILLAC, driver: {name: Timothy, type: stupid}, pubDate:16:00;
- name: SAAB, driver: {name: Julia, type: stupid}, pubDate:15:00;
Currently, I do have a solution in place, but it's not efficient and doesn't work well with infinite scroll. Using Meteor as an example:
// declare collections
Cars = Mongo.collection('cars', {
name: name,
type: [suv, sedan, sport],
driver: [object Driver]
pubDate: new Date()
});
Driver = Mongo.collection('cars', {
name: name,
lastName: lastName,
type: stupid // or clever
});
// declare helpers for client:
Template.carList.helpers({
'clever': function() {
return Cars.find({driver.type: 'clever'}, {sort: {pubDate: -1});
// returning only clever
},
'stupid': function() {
return Cars.find({driver.type: 'stupid'}, {sort: {pubDate: -1});
// returning only stupid
}
}):
In my HTML template using Blaze:
<template name='carList'>
...
{{#each clever}}
...
{{/each}}
{{#each stupid}}
...
{{/each}}
</template>
While this solution works, it lacks flexibility. If I need to add new sorting parameters, it becomes challenging. Furthermore, if driver types are stored in separate collections, such as Stupid & Clever, it complicates things even more.
I believe there must be a more elegant way to aggregate this data. What would you recommend? Thank you!