我已经编写了获取所有用户记录的查询
exports.index = function(req, res) {
Userdata.find(function(err, userdatas) {
if (err) {
return handleError(res, err);
}
console.log(userdatas);
});
};
控制台我收到以下文件
{
"_id" : ObjectId("584bc9ba420a6b189c510af6"),
"user_id" : 1,
"price" : 2000.0,
"type" : "credit",
},
{
"_id" : ObjectId("584bc9ba420a6b189c510af7"),
"user_id" : 1,
"price" : -1000.0,
"type" : "credit",
},
{
"_id" : ObjectId("584bc9ba420a6b189c510af8"),
"user_id" : 2,
"price" : 1000.0,
"type" : "credit",
}
现在我想计算总正数、总负数价格和总和(总正数-总负数)
一旦计算出,我需要在摘要集合中插入/更新
如果用户 ID 已经出现在摘要集合中,那么我们需要更新特定的用户文档
如果用户 ID 不存在,我们需要为该用户创建新文档
这里摘要集合已经存在 user_id = 1 ,因此我们需要更新此文档,并且 user_id = 2 不存在于摘要集合中,因此我们需要创建 .
{
"_id" : ObjectId("584bc9ba420a6b189c510af9"),
"user_id": 1,
"Totalpositiveprice": 3000.0,
"Totalnegativeprice": 0,
"Balanceprice": 3000.0
},
{
"_id" : ObjectId("584bc9ba420a6b189c510af9"),
"user_id": 3,
"Totalpositiveprice": 200.0,
"Totalnegativeprice": -190,
"Balanceprice": 10.0
}
我的预期结果:
{
"_id" : ObjectId("584bc9ba420a6b189c510af9"),
"user_id": "1",
"Totalpositiveprice": 5000.0,
"Totalnegativeprice": -1000.0,
"Balanceprice": 4000.0
},
{
"user_id": "2",
"Totalpositiveprice": 1000.0,
"Totalnegativeprice": 0,
"Balanceprice": 1000.0
},
{
"_id" : ObjectId("584bc9ba420a6b189c510af9"),
"user_id": 3,
"Totalpositiveprice": 200.0,
"Totalnegativeprice": -190,
"Balanceprice": 10.0
}
一旦计算出,我需要在摘要集合中插入/更新