在mongodb中展开空数组 [英] Unwind empty array in mongodb
问题描述
这与这个问题非常相似,但是,当使用类似方法时,我不断仅包含子文档的文档的列表.
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],
});
我想列出所有问题及其各自的分数.分数是voiceSchema中值"字段的总和.
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} ]
代替它(在 2 项目中粘贴[ { value : 0} ]
$cond
运算符数组).
另外,在这种情况下,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中展开空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!