This is very similar to this question, however, when using a similar approach, I keep getting a list of only the documents that contain subdocuments.
I have a simple schema with questions that can be up and down voted. My schema (I removed some fields for simplicity):
var mongoose = require('mongoose');
var voteSchema = new mongoose.Schema({
value: Number,
});
// Document schema for polls
exports.PollSchema = new mongoose.Schema({
question: { type: String, required: true },
votes: [voteSchema],
});
I want to have a list with all questions and their respective score. A score is the sum of the 'value' field in voteSchema.
I'm trying to use $cond to make sure the empty votes document is replaced with at least one vote subdocument with a value of 0. Unfortunately, when using it, all my totalScore fields are 0. If not using it, I get the correct totalScore, but only for the non empty ones.
Poll.aggregate([
{ $project: {
_id: 1,
question: 1,
totalScore : 1,
votes : { $cond : [ { $eq : ["$votes.length", 0]}, '$votes', [ { value : 0} ]] }
}},
{ $unwind: "$votes" },
{ $group: {
_id : "$_id",
question: { $first: "$question" },
totalScore : { $sum: "$votes.value" }
}},
], function(error, polls) {
console.dir(polls);
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…