我试图根据true / false值获取每个字段(ssl,maint,seo)的总计列表。我只需要知道它是否真实(它们有托管,或maint或seo)来为每个生成我的总计数。
主机架构:
var HostSchema = new Schema({
...
pkg: {
type: String,
required: [ true, 'Hosting Package is required' ]
},
ssl: { type: Boolean, required: true },
maint: { type: Boolean, required: true },
seo: { type: Boolean, required: true },
...
});
这是我目前的代码(它未完成):
// Grab all hosts with yes values for
Hosts.aggregate(
[
{ $match: { 'ssl': true }},
{ $group: {
'ssl': '$ssl',
'count': {'$sum': 1}
}
}
], function(err, hosts) {
console.log(hosts);
console.log(err);
if (err) console.log(err);
// INCOMPLETE -- Waiting to see the object structure of the above results.
var totals;
hosts.forEach(function(item, index) {
if (item)
totals.push({})
});
return res.render('./dashboard/dashboard', {
totals: totals,
user: req.user});
});
});
主机对象:
{ _id: 5a1f21d5bdaeb730da394900,
created_at: 2017-11-29T21:08:37.736Z,
updated_at: 2017-11-29T21:08:37.736Z,
domain: '1.com',
pkg: 'Not Hosted',
ssl: false,
maint: false,
seo: false,
__v: 0,
cms: [],
ftp: [] }
答案 0 :(得分:0)
我也能找到这个。这就是我想要做的事情:)
感谢您的帮助!
Hosts.aggregate(
[
{ $group: {
_id: 1,
ssl: {$sum: {$cond: [{$eq:['$ssl', true]}, 1, 0]}},
maint: {$sum: {$cond: [{$eq:['$maint', true]}, 1, 0]}},
seo: {$sum: {$cond: [{$eq:['$seo', true]}, 1, 0]}},
}
},
], function(err, hosts) {
返回:
[ { _id: 1, ssl: 3, maint: 2, seo: 2 } ]