Help with create if not exists and performance - Mongodb

Hey guys,

I want to make the query createIfNotExists using the MongoDB but focused in performance because this query will be executed thousands of time in the small period of time.

So, I tried to make this query using the updateOne, but it’s updating, and I don’t want to update, I just want to create If not exists

Metricas.updateOne(

      {

        $or: [

          {

            tipo_metrica_id,

            webinar_id,

            ip

          },

          {

            'participante.participante_id': participante?.participante_id,

            tipo_metrica_id,

            webinar_id

          }

        ]

      },

      {

        $set: {

          participante,

          tipo_metrica_id,

          webinar_id,

          ip,

          criado_em: new Date()

        }

      },

      { upsert: true },

    );

So, I want to create a register if these fields

{
tipo_metrica_id, 
webinar_id,
IP
}

OR

{
 'participante.participante_id': participante?.participante_id, 
tipo_metrica_id,
 webinar_id
}

Doesn’t exist in my database,

Thanks guys!

I am not too sure but I think that the problem is the query part of your updateOne.

The condition will be true if the condition is true, so only if a document exists, so an update is triggered. If you want the upsert the condition has to be negative. So if you want to create if it does not exist then you have negate the condition with $not.

We could help better if you share sample documents and values for the variables you use in the code you shared.