group in mongo excluding null values

前端 未结 3 2081
-上瘾入骨i
-上瘾入骨i 2021-01-17 10:58

I have mongo query which does the group operation on the documents.

I have almost got the expected results except that I want to refine the results without empty or

3条回答
  •  庸人自扰
    2021-01-17 11:45

    You need an extra $match pipeline step that will filter the incoming documents based on the embedded field "$productAttribute.colour" existing and not null:

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

提交回复
热议问题