node.js - 如何检查列中的任何值是否为空,它在猫鼬中计数值 1?
问题描述
如何检查列中的任何值是否为空,它在猫鼬中计数值 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
}
推荐阅读
- c - 如果 SPLIT 介于 4 和 7 之间,为什么这个程序会崩溃
- sql-server - SQL Server 连接字符串问题
- admob - admob 插页式广告有时显示黑屏
- vue.js - ipcRenderer.on('someevent') 在 VueJs 的渲染器进程中的 created() 或 mounted() 中?
- python - 根据文件名中的特定模式移动文件,同时保留文件夹结构
- testing - 如何通过指定元数据在 CI 中并行运行 TestCafe 测试
- sass - 迁移到 .NET 5.0 并使用 SASS 后,Blazor CSS 隔离不起作用且未添加范围标识符
- powershell - 通过网络媒体设备播放音频
- performance - 性能取决于索引类型
- c# - string.IndexOf 在 .NET 5.0 中返回不同的值