7

我有mongo查詢,它對文檔執行組操作。組在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 } 

我想刪除的行是否有任何組的字段值是空的或null在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 } 

回答

10

你需要一個額外的$match管道的步驟,將篩選基於嵌入式領域"$productAttribute.colour"傳入文件存在並且不爲空:

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

也許你應該在$ group操作之前使用$ match:{'color':{$ exists:true}}。隨着稀疏索引它將工作得很快。 並且不要在集合中存儲「null」字段,這將減少數據庫大小,並且將提高sparse索引的搜索速度(索引中的文檔減少 - >速度更快)