1 回答
TA贡献1804条经验 获得超2个赞
我对 MongoDB 还是个新手,但我认为这个聚合管道正是您要找的。也就是说,这是您应该使用文档自己研究的事情,但只要您了解思维过程,您就会学到一些东西,所以一切都很好!
[
{
$unwind: {
path: '$products',
// Here we are seperating each item in the products array of
// the user(I presumed your objects were users, or carts maybe)
// It will now be available to the next stage of the pipeline as
// a singular object for each item in the array,
// see the picture below for how this works practically.
}
},
{
$group: {
// Now we're going to restructure the object to
// center around the id field of the products, and
// at the same time we can add up the total price
// and count of each item.
_id: '$products.id', // This is the selector for the grouping process (in our case it's the id)
item: { $first: '$$ROOT.products' }, // this is me thinking you'll want access to the item in question for each total.
totalCount: { $sum: "$products.count" }, // adds to totalCount EACH $products.count that we have
totalPrice: { $sum: { $multiply: ["$products.price", '$products.count'] } }, // self explanatory
}
}
]
这就是 unwind 对你的数组和对象所做的
注意,出于实际原因,我修改/删除了一些变量名(_id、oid),您必须解析哪些变量名,如果复制粘贴,此代码很可能无法立即运行。
添加回答
举报