Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

865
Visualizações
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 Respostas
Responde à pergunta

0

You need an upsert in your case:

_, err := getIgnoreOffersCollection().UpdateOne(ctx, filter, update, options.Update().SetUpsert(true))
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda