【发布时间】:2017-04-28 09:30:43
【问题描述】:
我已经编写了获取所有用户记录的查询
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
}
计算后我需要在摘要集合中插入/更新
【问题讨论】:
-
注意:在预期结果中,值是错误的,应该是正23000,负-10000,user_id 1的余额13000?
标签: node.js mongodb mongoose mongodb-query