我试图使用聚合函数将数据转换为数组列表。下面是我的代码
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},发布于 2019-05-13 07:44:04
当您在多个字段中使用$group时,所有这些字段都在_id中,因此您在$group之后的文档将类似于您在问题中添加的结果,为了解决这个问题,可以将希望添加到顶层对象的字段添加到中。
在$group之后添加另一个管道以添加以下字段:
{
$addFields: {
total_quantity: "$_id.total_quantity",
parent_asin: "$_id.parent_asin",
product_asin: "$_id.product_asin"
}
}然后像以前一样做$project。
发布于 2019-05-13 10:53:54
在项目中使用_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
}
}
]);
https://stackoverflow.com/questions/56104751
复制相似问题