问题描述
这与 this question 非常相似,但是,当使用类似的方法时,我不断得到仅包含子文档的文档列表.
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],
});
我想要一个包含所有问题及其各自分数的列表.分数是 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.
我正在尝试使用 $cond 来确保将空投票文档替换为至少一个值为 0 的投票子文档.不幸的是,使用它时,我所有的 totalScore 字段都是 0.如果不使用它,我得到了正确的 totalScore,但仅适用于非空的.
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);
});
推荐答案
如果你的空votes
是null
(不存在),尝试使用:
If your empty votes
is null
(not exists), try to use:
{ $ifNull : [ "$votes", [ { value : 0 } ] ] }
代替:
{ $cond : [ { $eq : [ "$votes.length", 0 ] }, '$votes', [ { value : 0 } ] ] }
如果你的空 votes
是 []
(空数组):
If your empty votes
is []
(empty array):
{ $cond : [ { $eq : [ "$votes", [] ] }, [ { value : 0 } ], '$votes' ] }
还有一些关于 $cond
运算符:
And some about $cond
operator:
它的语法:{ $cond: [ <boolean-expression>, <true-case>, <false-case>] }代码>.
但是你用过,比如:{ $cond: [ <boolean-expression>, <false-case>, <true-case>] }代码>.
如果 votes
不存在或为空数组(布尔条件为 true),您应该使用 [ { value : 0} ]
代替它(将 [ { value : 0} ]
粘贴到 $cond
运算符数组的 2 项中).
此外,在这种情况下,length
属性不可访问.
If votes
not exists or empty array (boolean condition is true) you should use [ { value : 0} ]
instead of it (paste [ { value : 0} ]
in 2 item of $cond
operator array).
Also, length
property is not accessable in this case.
这篇关于在 mongodb 中展开空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!