我如何在我的MongoDB数组中选择一个特殊的字段并将其求和
我有一个MongoDB模式,有时我有一个数组,有时我有20个以上的数组值,每个数组都有一个字段值,我想将这些值求和并将其总和插入MongoDB的另一个字段中。这是我想说的,这是我的架构,我如何才能将插入到架构中的每个包装阵列的权重值加在一起,并使其成为我的总重量架构]
{
"status": "In warehouse",
"paymentStatus": "incomplete",
"_id": "5d8b56476a3e4ae2d01f2953",
"unitNo": "0002",
"warehouseNo": "0001",
"trackingNo": "FPZ848505936",
"packages": [
{
"date": "2019-09-26T06:30:39.561Z",
"_id": "5d8c5b0f756838f78d5205d7",
"category": "chil",
"quantity": "177",
"description": "a valueablegoods",
"width": 15,
"itemweight": 123,
"length": 17,
"height": 21,
"dimension": 31.25903614457831,
"weight": 32.25903614457831
},
{
"date": "2019-09-26T06:30:39.561Z",
"_id": "5d8c5b0f756838f78d5202dd,
"category": "chil",
"quantity": "177",
"description": "a valueablegoods",
"width": 15,
"itemweight": 123,
"length": 17,
"height": 21,
"dimension": 35.25903614457831,
"weight": 30
},
{
"date": "2019-09-26T06:30:39.561Z",
"_id": "5d8c5b0f756838f78d51aeq",
"category": "chil",
"quantity": "177",
"description": "a valueablegoods",
"width": 15,
"itemweight": 123,
"length": 17,
"height": 21,
"dimension": 32.25903614457831,
"weight": 44
}
],
"totalWeigth": "This should add all weight value in my packages array together and if it is only 1 it should brings only the one"
"date": "2019-09-25T11:57:59.359Z",
"__v": 0
}
这是将包添加到包数组字段的api路由,我希望在添加或更新新包时随时更新totalWeight
// @route POST api/admins/addshipment/:unitNo
// @desc Add shipment for each customer
// @access Private
router.post(
'/addshipment/:unitNo',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Shipments.findOne({unitNo: req.params.unitNo}, {paymentStatus: "incomplete"})
.then(shipments => {
if(shipments === null || shipments.paymentStatus === "complete"){
const errwarehouse = "This user doesn't have an existing warehouse";
return res.status(404).json(errwarehouse);
}else{
if (shipments.paymentStatus === "incomplete") {
function getPrice(){
if (initial > dimension){
return initial
}else if(initial === dimension) {
return initial
}else{
return dimension
}
}
const newPackages = {
category: req.body.category,
quantity: req.body.quantity,
description: req.body.description,
width: req.body.width,
itemweight: req.body.itemweight,
length: req.body.length,
height: req.body.height,
dimension,
weight: getPrice(),
};
Shipments.findOneAndUpdate({unitNo: req.params.unitNo ,paymentStatus: "incomplete"},
{"$push": {"packages": newPackages}}, {totalWeight: {"$sum" : {"packages.weight"}}}) //Here is were i add the package to the package array and here is where i tried sumup packages.weight for every time i add new package
.then(shipments=> res.json(shipments))
}
}
});
});
谢谢
回答如下: var users =db.users.aggregate([
{$unwind:"$packages"},
{
$group:
{
_id: "$_id",
totalWeigth: { $sum: "$packages.weight" }
}
}
]).toArray()
users.forEach((ele)=>{
db.users.update({_id:ele._id},{$set:{totalWeigth:ele.totalWeigth}})
})