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),您必須解析哪些變量名,如果復制粘貼,此代碼很可能無法立即運行。
添加回答
舉報
