Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

857
Views
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 answers
Answer question

0

You need an upsert in your case:

_, err := getIgnoreOffersCollection().UpdateOne(ctx, filter, update, options.Update().SetUpsert(true))
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!