Mongodb 在mongo中使用$unwind和group by函数时出错。。。?

Mongodb 在mongo中使用$unwind和group by函数时出错。。。?,mongodb,mongoose,group-by,mongodb-query,Mongodb,Mongoose,Group By,Mongodb Query,}, 上面是我的mongo集合结构,在对属性键应用$unwind时,然后应用逐属性slug,然后获得两次逐组集合。。 我的问题是 { "sku" : "sku", "price" : 0, "name" : "name", "attributes" : [ { "name" : "fit", "value" : "Regular", "slug" : "regular", "fit" : "regular" },

},

上面是我的mongo集合结构,在对属性键应用$unwind时,然后应用逐属性slug,然后获得两次逐组集合。。 我的问题是

{
"sku" : "sku",
"price" : 0,
"name" : "name",
"attributes" : [
    {
        "name" : "fit",
        "value" : "Regular",
        "slug" : "regular",
        "fit" : "regular"
    },
    {
        "name" : "color_family",
        "value" : "Red",
        "slug" : "red",
        "color_family" : "red"
    },
    {
        "name" : "occassion",
        "value" : "Casual",
        "slug" : "casual",
        "occassion" : "casual"
    }
]
答案是

db.products_mumbai.aggregate(
  {$unwind : "$attributes"},
  {$group : { _id : "$attributes.color_family", quantity : { $sum:1 } } })

这完全是正常的行为

当你展开一个数组时,考虑MangGDB作为新的文档添加到你的数组中。在每个示例中,$unwind将导致有3个文档:

{ "_id" : "red", "quantity" : 21 }
{ "_id" : null, "quantity" : 126 }
然后,你让他按属性分组。由于只有一个文档具有此密钥,因此其中一个文档为红色,其他所有文档为空

编辑: 如果要避免
null
值,则在
$unwind
之前
$group
之后,必须添加
$match

{
"sku" : "sku",
"price" : 0,
"name" : "name",
"attributes" :
    {
        "name" : "fit",
        "value" : "Regular",
        "slug" : "regular",
        "fit" : "regular"
    }
},
{
"sku" : "sku",
"price" : 0,
"name" : "name",
"attributes" :
    {
        "name" : "color_family",
        "value" : "Red",
        "slug" : "red",
        "color_family" : "red"
    }
},
{
"sku" : "sku",
"price" : 0,
"name" : "name",
"attributes" :
    {
        "name" : "occassion",
        "value" : "Casual",
        "slug" : "casual",
        "occassion" : "casual"
    }
}

如果输出中不需要null,则可以向聚合中添加其他匹配项:

{ $match : { "attributes.color_family": {$exists:true} } }

但我不想在group by中使用空值。。。那么我要做什么呢???@AsheshKhatri我已经编辑了我的答案来删除空值。@AsheshKhatri如果答案适合你,请不要忘记验证答案,这样其他人就会得到正确的答案。我不希望在分组中使用空值…那么我要做的是…?按照我的答案中的设置,我会将$match放在$group之前。我认为在大型场景中,它会有更好的表现。@ConstantinGuay是的,这是真的。
db.products_mumbai.aggregate(
  {$unwind : "$attributes"},
  {$group : { _id : "$attributes.color_family", quantity : { $sum:1 } } }),
  {$match : { _id : {$ne: null }}}
)