如何检查列中的任何值是否为空,它应该在 Mongoose 中计数值1? 我试过了
data: {
$max: {
$cond: [{
$or: [{ $eq: ["$mycolumn", null] },
// { $eq: [ "$anotherField","value"] }
]
},
0,
1]
}
},
但这返回 null。如何解决这个问题?提前致谢
我的收藏是
{ _id: 1, item: null ,name:sam,status:open},
{ _id: 2, item: null ,name:arun,status:open},
{ _id: 2, item: 1,name:arun,status:close},
{ _id: 2, item: 1,name:sam,status:close},
我还必须通过分组状态进行检索。
最佳答案
请尝试这个:
db.yourCollectionName.aggregate([{$group: {_id : '$status',
sumOfItem : {$sum : {$cond: [ { $eq: [ "$item", null ] }, 1, '$item' ]}}}}])
(Or)
/** If you've to check if field exists & also field value == null to return 1
or original item value try below - but this might not be needed,
if you don't want to check field exists cause `$ifNull` internally does both checks */
db.yourCollectionName.aggregate([{$group: {_id : '$status', sumOfItem : {$sum : { $ifNull: [ "$item", 1 ] }}}}])
收集数据:
/* 1 */
{
"_id" : 1.0,
"item" : null,
"name" : "sam",
"status" : "open"
}
/* 2 */
{
"_id" : 2.0,
"item" : null,
"name" : "arun",
"status" : "open"
}
/* 3 */
{
"_id" : 3.0,
"item" : 1.0,
"name" : "arun",
"status" : "close"
}
/* 4 */
{
"_id" : 4.0,
"item" : 1.0,
"name" : "sam",
"status" : "close"
}
/* 5 */
{
"_id" : 5.0,
"item" : 3,
"name" : "sam3",
"status" : "open"
}
结果:
/* 1 */
{
"_id" : "close",
"sumOfItem" : 2.0
}
/* 2 */
{
"_id" : "open",
"sumOfItem" : 5.0
}
以防万一,如果您不想要项目字段的总和,而只想要总的 open
和 close
状态(您不必检查 null
),请尝试以下操作:
db.yourCollectionName.aggregate([{$group: {_id : '$status', total : {$sum : 1}}}])
**Result :**
/* 1 */
{
"_id" : "close",
"total" : 2.0
}
/* 2 */
{
"_id" : "open",
"total" : 3.0
}
关于node.js - 如何检查列中的任何值是否为空,它应该在 Mongoose 中计数值1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59588064/