我有Mongo查询,它对文档进行分组操作。
我几乎得到了预期的结果,除了我想优化没有空或空值的结果。
当前我的查询如下:

db.productMetadata.aggregate([{$group:{"_id":{"color":"$productAttribute.colour","gender":"$productAttribute.gender"},"count" : {$sum : 1}}}]);

结果是这样的:
{ "_id" : { "color" : "BLUE", "gender" : "MEN" }, "count" : 1 }
{ "_id" : {  }, "count" : 4 }
{ "_id" : { "color" : "NA", "gender" : "WOMEN" }, "count" : 1 }
{ "_id" : { "color" : "BLACK", "gender" : "MEN" }, "count" : 1 }
{ "_id" : { "color" : "BROWN", "gender" : "WOMEN" }, "count" : 1 }
{ "_id" : { "gender" : "MEN" }, "count" : 2 }
{ "_id" : { "color" : "BEIGE", "gender" : "MEN" }, "count" : 1 }
{ "_id" : { "color" : "BROWN", "gender" : "MEN" }, "count" : 1 }

如果数据库的实际数据中GroupBy字段值为空或为空,我希望删除这些行。
例外结果应如下所示:
{ "_id" : { "color" : "BLUE", "gender" : "MEN" }, "count" : 1 }
{ "_id" : { "color" : "NA", "gender" : "WOMEN" }, "count" : 1 }
{ "_id" : { "color" : "BLACK", "gender" : "MEN" }, "count" : 1 }
{ "_id" : { "color" : "BROWN", "gender" : "WOMEN" }, "count" : 1 }
{ "_id" : { "color" : "BEIGE", "gender" : "MEN" }, "count" : 1 }
{ "_id" : { "color" : "BROWN", "gender" : "MEN" }, "count" : 1 }

最佳答案

您需要一个额外的管道步骤,该步骤将根据嵌入字段“existing”和“not null”筛选传入的文档:

db.productMetadata.aggregate([
    {
        "$match": {
            "productAttribute.colour": { "$exists": true, "$ne": null }
        }
    },
    {
        $group:{
            "_id": {
                "color": "$productAttribute.colour",
                "gender": "$productAttribute.gender"
            },
            "count": {
                $sum : 1
            }
        }
    }
]);

关于mongodb - mongo中的组,不包括空值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33123396/

10-16 14:23