Я видел подобный вопрос , но у него нет ответа, поэтому он не отвечает на мой вопрос.
Как сгруппировать массивы на основе другого массива в агрегации mongodb?
Предположим, у вас есть следующие схемы:
PollSchema
const PollSchema = new mongoose.Schema({
numberOfChoices: {
type: Number,
required: true,
min: [1, "Number of choices must be at least 1"],
max: [10, "Number of choices cannot be more than 10"],
},
arrayOfNamesOfChoices:[{
name: {
type: String,
required: true,
},
}],
});
CastedVotedSchema
const CastedVoteSchema = new mongoose.Schema({
voter: {
type: String,
required: true,
},
choice: {
type: Number,
required: true,
min:0,
max:9
},
});
Как я могу в агрегации mongodb отсортировать castedVotes в массивы на основе их выбора. Например, рассмотрим образец данных ниже:
Poll = {
numberOfChoices: 3
arrayOfNamesOfChoices: [
{name:'choiceA'},{name:'choiceB'},{name:'choiceC'}
]
}
CastedVotes = [
{voter: 'Juzi', choice: 0},{voter: 'Juma', choice: 0},{voter: 'Jane', choice: 0},
{voter: 'Jamo', choice: 1},{voter: 'Juju', choice: 1},{voter: 'Jana', choice: 1},
]
ПРИМЕЧАНИЕ: Не набрано ни одного голоса в choiceC
Я пытаюсь создать запрос агрегации, который возвращает массив на основе каждого выбора. Например (см. Ниже).
//below is the result I desire to have
{
totalVotes:[
{voter: 'Juzi', choice: 0},{voter: 'Juma', choice: 0},{voter: 'Jane', choice: 0},
{voter: 'Jamo', choice: 1},{voter: 'Juju', choice: 1},{voter: 'Jana', choice: 1},
],
choiceA:[{voter: 'Juzi', choice: 0},{voter: 'Juma', choice: 0},{voter: 'Jane', choice: 0}],
choiceB:[{voter: 'Jamo', choice: 1},{voter: 'Juju', choice: 1},{voter: 'Jana', choice: 1}],
choiceC:[],// the choiceC array should be present and empty
}
Как сгруппировать массив Poll.arrayOfNamesOfChoices
на основе массива *1027* в агрегацию mongodb?