在 mongo 中分组,不包括空值 [英] group in mongo excluding null values
本文介绍了在 mongo 中分组,不包括空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 mongo 查询,它对文档进行组操作.
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 null values.
目前我的查询如下所示:
Currently my query looks like this:
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 }
如果 DB 的实际数据中任何 group by 字段值为空或 null,我想删除行.
I want to remove the rows if any of the group by field values are empty or null in the actual data of DB.
异常结果应如下所示:
{ "_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 }
推荐答案
你需要一个额外的$match
管道步骤,将根据现有的嵌入字段 "$productAttribute.colour"
过滤传入的文档并且不为空:
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
}
}
}
]);
这篇关于在 mongo 中分组,不包括空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文