根据类别更新对象类型的mongodb字段

时间:2019-05-24 10:47:54

标签: javascript node.js mongodb mongodb-query aggregation-framework

我的MongoDB集合中有以下文档。

{
    "_id" : ObjectId("5ce34ac6a2f25b2448b9b3a3"),
    "userId" : ObjectId("5ce34ac6a2f25b2448b9b3a0"),
    "providers" : [ 
        "1689736266", 
        "1598763690", 
        "1528069614", 
        "1831364272", 
        "1548463045", 
        "1245301159", 
        "1386616399", 
        "1790775971", 
        "1629462130", 
        "1992169783"
    ],
    "countByType" : {
        "doctors" : 0,
        "labs" : 0,
        "hospitals" : 0,
        "imagingCenters" : 0
    }
}

类别是医生,实验室,医院和成像中心。 问题在于,对于一​​个没有医院类别的特定用户,另一个用户可能具有。因此,我需要根据用户类别更新MongoDB中的countByType字段。如果用户不包含医生类别,则无需在MongoDB中进行更新。 当我尝试更新计数时,不存在的类别变为空值。

请参阅更新查询:

let updateProviderId = await userProviderCollection.update(
      regUserId, {
          $set:  {
              providers: providernpiId,
              countByType: {
                  "doctors" : counts.doctor,
                    "labs" : counts.lab,
                    "hospitals" : counts.hospital,
                    "imagingCenters" : counts.imagingcenter
              }
           }

      });

现在我得到的输出为

"countByType" : {
        "doctors" : 6,
        "labs" : null,
        "hospitals" : null,
        "imagingCenters" : null
    }

预期输出:

"countByType" : {
        "doctors" : 6,
        "labs" : 1,
        "hospitals" : 0,
        "imagingCenters" : 0
    }

如果用户类别包含医生和实验室。

1 个答案:

答案 0 :(得分:0)

您只需要预先检查键在counts对象中是否存在,如果要更新mongodb中的嵌套对象键,则需要使用点运算符指定完整的键路径,如下所示:< / p>

let setObj = {
  providers: providernpiId
};
let {
  doctor,
  lab,
  hospital,
  imagingcenter
} = counts;
doctor && (setObj["countByType.doctor"] = doctor);
lab && (setObj["countByType.lab"] = lab);
hospital && (setObj["countByType.hospital"] = hospital);
imagingcenter && (setObj["countByType.imagingcenter"] = imagingcenter);
let updateProviderId = await userProviderCollection.update(
  regUserId, {
    $set: setObj
  });

相关问题