聚合功能增强,包括多个不带_id字段的字段

时间:2019-05-13 01:09:21

标签: mongodb

我正在尝试使用聚合函数将数据转换为数组列表。 下面是我的代码

Quantity.aggregate([
    {$group: {
                    _id: {
                        product_asin: "$productAsin",
                        parent_asin: "$parentProductAsin",
                        total_quantity: "$totalQuantity" ,                  
                    }
    }},
     { "$project":{product_asin:true,parent_asin:true,total_quantity:true,_id:false}}
 ])

这给了我以下输出

[ {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {} ]

如果我删除$ project,则会得到下面的输出,并带有_id和数据

[ { _id:
     { product_asin: 'asdasd',
       parent_asin: 'Dasda',
       total_quantity: '0' } },
  { _id:
     { product_asin: 'dfasf',
       parent_asin: 'fasd',
       total_quantity: '0' } },
  { _id:
     { product_asin: 'fasd',
       parent_asin: 'fasd',
       total_quantity: '0' } },
  { _id:
     { product_asin: 'fasd',
       parent_asin: 'asd',
       total_quantity: '0' } },
  { _id:
     { product_asin: 'fsda',
       parent_asin: 'asdf',
       total_quantity: '0' } },
  { _id:
     { product_asin: 'asd',
       parent_asin: 'asd',
       total_quantity: '0' } },
  { _id:
     { product_asin: 'fsda',
       parent_asin: 'asdf',
       total_quantity: '0' } },
  { _id:
     { product_asin: 'fasd',
       parent_asin: 'asdf',
       total_quantity: '0' } },
  { _id:
     { product_asin: 'fsda',
       parent_asin: 'asdf',
       total_quantity: '0' } },
  { _id:
     { product_asin: 'fsda',
       parent_asin: 'asdf',
       total_quantity: '0' } },
  { _id:
     { product_asin: 'fsadfsa',
       parent_asin: 'asdf',
       total_quantity: '0' } },
  { _id:
     { product_asin: 'asdf',
       parent_asin: 'sadf',
       total_quantity: '0' } },
  { _id:
     { product_asin: 'fsda',
       parent_asin: 'asdfasdf',
       total_quantity: '0' } },
  { _id:
     { product_asin: 'fasda',
       parent_asin: 'fasd',
       total_quantity: '0' } } ]

问题: 如何更改聚合函数代码以获取以下输出

{product_asin: 'IBM', parent_asin: 13, total_quantity: 12},
  {product_asin: 'IB2342M', parent_asin: 13, total_quantity: 12},
  {product_asin: 'I44234BM', parent_asin: 14,  total_quantity: 12},

2 个答案:

答案 0 :(得分:1)

当您将$group与多个字段一起使用时,所有这些字段都放在_id内,因此$group之后的文档看起来就像您在问题中添加的结果一样, 您可以将想要添加的字段添加到顶级对象。

在您的$group之后添加另一个管道以添加以下字段:

{
    $addFields: {
        total_quantity: "$_id.total_quantity",
        parent_asin: "$_id.parent_asin",
        product_asin: "$_id.product_asin"
    }
}

然后像以前一样执行$project

答案 1 :(得分:1)

在这样的项目中使用_id

访问密钥:

Quantity.aggregate([{
    $group: {
      _id: {
        product_asin: "$productAsin",
        parent_asin: "$parentProductAsin",
        total_quantity: "$totalQuantity"
      }
    }
  },
  {
    $project: {
      product_asin: "$_id.product_asin",
      parent_asin: "$_id.parent_asin",
      total_quantity: "$_id.total_quantity",
      _id: 0
    }
  }
]);