首页 > 解决方案 > 如何检查列中的任何值是否为空,它在猫鼬中计数值 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},


我也必须通过分组状态检索。

标签: node.jsmongodbmongoose

解决方案


请试试这个:

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
}

推荐阅读