使用$ unwind时获取错误,然后在mongo中使用该功能组...

时间:2015-12-11 08:55:00

标签: mongodb mongoose group-by mongodb-query

{
"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"
    }
]

},

上面是我的mongo集合结构,同时将$ unwind应用到我的属性键,然后按属性slug应用group,然后按集合逐次获取两次.. 我的查询是

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

回复是

{ "_id" : "red", "quantity" : 21 }
{ "_id" : null, "quantity" : 126 }

2 个答案:

答案 0 :(得分:0)

这完全是一种正常行为。

当您展开数组时,请考虑将MongoDB添加为数组中的新文档。在每个示例的情况下,$ unwind将导致有3个文档:

{
"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"
    }
}

然后,你要求他按attributes.color_family进行分组。由于只有一个文档具有此密钥,因此您将获得一个红色,而其他所有文档则为null。

修改 如果您想避免null值,那么在$unwind之前 $group后,您必须添加$match

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

答案 1 :(得分:0)

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

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