And*_*pon 6 mongodb aggregation-framework
这与此问题非常相似,但是,当使用类似的方法时,我不断获得仅包含子文档的文档的列表.
我有一个简单的架构,可以上下投票的问题.我的架构(为简单起见,我删除了一些字段):
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],
});
Run Code Online (Sandbox Code Playgroud)
我希望列出所有问题和各自的分数.得分是voteSchema中"值"字段的总和.
我正在尝试使用$ cond来确保空投票文档被替换为至少一个值为0的投票子文档.不幸的是,当使用它时,我的所有totalScore字段都是0.如果不使用它,我得到了正确的总分数,但仅适用于非空分数.
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);
});
Run Code Online (Sandbox Code Playgroud)
Iva*_*Srb 20
如果您的空votes
是null
(不存在),请尝试使用:
{ $ifNull : [ "$votes", [ { value : 0 } ] ] }
Run Code Online (Sandbox Code Playgroud)
代替:
{ $cond : [ { $eq : [ "$votes.length", 0 ] }, '$votes', [ { value : 0 } ] ] }
Run Code Online (Sandbox Code Playgroud)
如果你的空votes
是[]
(空数组):
{ $cond : [ { $eq : [ "$votes", [] ] }, [ { value : 0 } ], '$votes' ] }
Run Code Online (Sandbox Code Playgroud)
还有一些关于$cond
运营商:
它的语法:{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }
.
但是你用它,比如:{ $cond: [ <boolean-expression>, <false-case>, <true-case> ] }
.
如果votes
不存在或空数组(布尔条件为真),则应使用[ { value : 0} ]
而不是它(粘贴[ { value : 0} ]
在2个$cond
运算符数组项中).
此外,length
在这种情况下,属性不可访问.
归档时间: |
|
查看次数: |
4919 次 |
最近记录: |