Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

872
Vistas
Golang Mongodb $push and if doesn't exist create

So basically I have this struct that has to appear in mongoDb and I have to write a query witch would firstly check if an object with the profileID already exists it would push a new offer id to the existing objects offers array. And if an Object with the profileID does not exist it would create one and add the offer id to the offers array. Is it possible to do it in one query? if so could anyone help me on how it could be implemented?

type IgnoreOffer struct {
    ProfileID primitive.ObjectID   `json:"profileID" bson:"profileID"`
    Offers    []primitive.ObjectID `json:"offers,omitempty" bson:"offers,omitempty"`
}

Here's my code for however it does not create a new object in the database.

func getIgnoreOffersCollection() *mongo.Collection {
    return db.GetMongoCollection("ignoreOffers")
}

func ignoreOffer(profileId primitive.ObjectID, offerId primitive.ObjectID) error {
    var offer IgnoreOffer
    offer.ProfileID = profileId
    ctx, _ := db.GetTimeoutContext()
    filter := bson.M{"profileID": profileId}
    update := bson.M{
        "$set": bson.M{
            "updatedAt": time.Now(),
        },
        "$push": bson.M{
            "offers": offerId,
        },
    }

    _, err := getIgnoreOffersCollection().UpdateOne(ctx, filter, update)
    if err != nil {
        log.Error("could not update ignoreOffer collection, err: ", err)
        return err
    }
    return nil
}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You need an upsert in your case:

_, err := getIgnoreOffersCollection().UpdateOne(ctx, filter, update, options.Update().SetUpsert(true))
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda