node.js - 如何检查列中的任何值是否为空,它应该在 Mongoose 中计数值1?

标签 node.js mongodb mongoose

如何检查列中的任何值是否为空,它应该在 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
}

以防万一,如果您不想要项目字段的总和,而只想要总的 openclose 状态(您不必检查 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/

相关文章:

node.js - 使用 nginx 作为负载均衡器的意外测试结果

javascript - 客户端和服务器 Meteor 之间的共享集合

javascript - 从 Sails.js 中的 skipper-gridfs 下载图像

node.js - 如何查找一个或另一个字段与某个值匹配的文档?

node.js - Mongoose 聚合查询 $match 中的 $max

javascript - 如何在 Nodejs 上使用 readlineSync

node.js - 使用 IISNode 在 IIS 中托管 Nodejs 应用程序时如何启用静态文件(和较少的支持)

mongodb - 如何在 mongodb 中使用 $lookup 连接多个集合

javascript - Mongoose:查找、修改、保存

javascript - 如果发布请求成功则关闭对话框