【发布时间】:2017-04-25 18:05:37
【问题描述】:
以下是我的用户定价收集数据
{
"_id" : ObjectId("584bc9ba420a6b189c510af6"),
"user_id" : 1,
"mobilenumber":"01234",
"price" : 2000.0,
"type" : "credit",
},
{
"_id" : ObjectId("584bc9ba420a6b189c510af6"),
"user_id" : 1,
"mobilenumber":"01234",
"price" : -1000.0,
"type" : "credit",
},
{
"_id" : ObjectId("584bc9ba420a6b189c3323w23"),
"user_id" : 2,
"mobilenumber":"04321",
"price" : 1000.0,
"type" : "credit",
}
在这里我想计算所有用户的总正价和总负价,我需要检查该用户是否存在于摘要集合中。如果记录不存在,我们需要在摘要集合中创建文档,如果存在我们需要更新 "Totalpositiveprice","Totalnegativeprice" 和 "Balanceprice"
在汇总表中已经存在这条记录
{
"user_id": "1",
"mobilenumber":"01234",
"Totalpositiveprice": 3000.0,
"Totalnegativeprice": 0,
"Balanceprice": 3000.0
},
{
"user_id": "3",
"mobilenumber":"05555",
"Totalpositiveprice": 1000.0,
"Totalnegativeprice": -100,
"Balanceprice": 900.0
}
我们需要更新“mobilenumber”的文档:“01234”,
我们需要为“mobilenumber”创建新文档:“04321”,
"mobilenumber":"05555" 无需做任何事情,因为用户定价中没有任何内容
最后我应该得到这样的摘要集合
{
"user_id": "1",
"mobilenumber":"01234"
"Totalpositiveprice": 5000.0,
"Totalnegativeprice": -1000.0,
"Balanceprice": 4000.0
},
{
"user_id": "2",
"mobilenumber":"04321"
"Totalpositiveprice": 1000.0,
"Totalnegativeprice": 0,
"Balanceprice": 1000.0
},
{
"user_id": "3",
"mobilenumber":"05555",
"Totalpositiveprice": 1000.0,
"Totalnegativeprice": -100,
"Balanceprice": 900.0
}
【问题讨论】:
-
如果余额是指来自 1 个用户的所有价格的总和,那么您在下面有一个答案
-
差不多,但他/她也想导出到另一个集合中
-
@ShaishabRoy OP 询问的原因是因为他不知道如何进行条件求和而不是如何将结果导出到新集合。
-
同意你@Styvane
标签: mongodb mongodb-query aggregation-framework robo3t