简化mongodb查询if(变量是否存在)

时间:2014-03-21 14:29:33

标签: mongodb

我正从游戏客户端收到两个或两个变量中的一个: 金额和金额2

我有代码在mongo数据库中执行任务,无论是对于这两个变量还是对于其中一个变量:

if(amount && amount2) mMissionUser.update_task({id_user: id_user, id_mission: id_mission,     "tasks.id_task": id_task}, { $set: { "tasks.$.counter": amount, "tasks.$.counter2": amount2 } }, process);
else if(amount && !amount2) mMissionUser.update_task({id_user: id_user, id_mission: id_mission, "tasks.id_task": id_task}, { $set: { "tasks.$.counter": amount } }, process);
else if(!amount && amount2) mMissionUser.update_task({id_user: id_user, id_mission: id_mission, "tasks.id_task": id_task}, { $set: { "tasks.$.counter2": amount2 } }, process);

您是否知道如何在单行MONGODB查询中对其进行简化?

1 个答案:

答案 0 :(得分:1)

以编程方式构建$set对象,然后使用常见update调用应用它:

var set = {};
if (amount) set["tasks.$.counter"] = amount;
if (amount2) set["tasks.$.counter2"] = amount2;
mMissionUser.update_task(
    {id_user: id_user, id_mission: id_mission, "tasks.id_task": id_task}, 
    {$set: set}, 
    process);