Агрегация MongoDB - ваш лучший вариант для специальных запросов, подобных этому. Это пример того, как вы можете использовать агрегирование MongoDB для достижения результата, который вы описали в вопросе:
const pipeline = [
{
$group: {
_id: null, // This is set to null so that we can touch all the documents in the collecion
name: { $addToSet: '$name' }, // Add all the name uniquely into an array
lastName: { $addToSet: '$lastName' }, // Add all the lastName uniquely into an array
maxAge: { $max: '$age' }, // Get the max age
minAge: { $min: '$age' }, // Get the min age
maxRate: { $max: '$rate' }, // Get the max rate
minRate: { $min: '$rate' } // Get the min rate
}
},
{
$project: { // Reshape the output document
_id: false,
name: '$name',
lastName: '$lastName',
age: ['$minAge', '$maxAge'],
rate: ['$minRate', '$maxRate']
}
}
]
// Let's say the data is stored in collections "users"
db.users.aggregate(pipeline);
/* This would output something like this:
{
"name" : [ "John", "Elliot" ],
"lastName" : [ "Doe", "Snow", "Anderson" ],
"age" : [ 23, 28 ],
"rate" : [ 333, 555 ]
}
*/
Что касается производительности, то она действительно зависит от размера вашей коллекции, так как этот запрос будет наиболееСкорее всего, придется сканировать каждый документ в коллекции, однако это все равно будет лучшим вариантом, учитывая возможную динамику запроса, как вы объяснили в комментарии к вопросу.