'How to update document if exists else insert new document in mongo db

This Document Should be inserted if it does not find match

 insertDoc = %{
      "groupId" => groupObjectId,
      "userId" => userObjectId,
      "isActive" => true,
      "month" => dateTimeMap["month"],
      "year" => dateTimeMap["year"],
      "attendanceStaff" =>[%{
        "attendance" => status,
        "attendanceAt" => dateObject,
        "date" =>  "#{ String.slice("0"<>""<>to_string(dateTimeMap["day"]), -2, 2)}-#{String.slice("0"<>""<>to_string(dateTimeMap["month"]), -2, 2)}-#{dateTimeMap["year"]}",
        "dateString" => "#{dateTimeMap["year"]}#{String.slice("0"<>""<>to_string(dateTimeMap["month"]), -2, 2)}#{ String.slice("0"<>""<>to_string(dateTimeMap["day"]), -2, 2)}",
        "attendanceTakenById" => loginUserObjectId,
        "attendanceTakenByName" => loginUserName,
        "time" => indiaTime
      }]
    }

if it gets matched this document should be push to the array

    updateDoc = %{
        "attendance" => status,
        "attendanceAt" => dateObject,
        "date" =>  "#{ String.slice("0"<>""<>to_string(dateTimeMap["day"]), -2, 2)}-#{String.slice("0"<>""<>to_string(dateTimeMap["month"]), -2, 2)}-#{dateTimeMap["year"]}",
        "dateString" => "#{dateTimeMap["year"]}#{String.slice("0"<>""<>to_string(dateTimeMap["month"]), -2, 2)}#{ String.slice("0"<>""<>to_string(dateTimeMap["day"]), -2, 2)}",
        "attendanceTakenById" => loginUserObjectId,
        "attendanceTakenByName" => loginUserName,
        "time" => indiaTime
    }

Mongo query used for upsert

 filter = %{
    "userId" => userObjectId,
    "month" => month,
   }
   update = %{
   "$setOnInsert" => insertDoc,
   "$push" => %{"attendanceStaff" => updateDoc}
   }
   project = %{
     "upsert" => true,
   }
  Mongo.update_one(@conn, @staff_attendance_db, filter, update, [projection: project])

output

 {:error, %Mongo.Error{code: 40, message: "Updating the path 'attendanceStaff' would create a conflict at 'attendanceStaff'"}}

Thank you



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source