Docs Menu

Docs HomeGo

Insert or Update in a Single Operation

On this page

  • Overview
  • Upsert
  • Additional Information

In this guide, you can learn how to specify an upsert.

To run the example in this guide, load the sample data into the tea.ratings collection with the following snippet:

coll := client.Database("tea").Collection("ratings")
docs := []interface{}{
bson.D{{"type", "Masala"}, {"rating", 10}},
bson.D{{"type", "Assam"}, {"rating", 5}},
}
result, err := coll.InsertMany(context.TODO(), docs)
if err != nil {
panic(err)
}
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))

Tip

Non-existent Databases and Collections

If the necessary database and collection don't exist when you perform a write operation, the server implicitly creates them.

Each document contains a rating for a type of tea that corresponds to the type and rating fields.

Applications use insert and update operations to store and modify data. Sometimes, you need to choose between an insert and an update operation depending on whether the document exists. MongoDB simplifies this decision for us with an upsert option.

An upsert performs one of the following actions:

  • Update documents that match your query filter

  • Insert a document if there are no matches to your query filter

You can specify an upsert by passing true to the SetUpsert() method in the options of the following write operation methods:

  • UpdateOne()

  • UpdateByID()

  • UpdateMany()

  • ReplaceOne()

  • FindOneAndUpdate()

  • FindOneAndReplace()

Tip

If you don't specify an upsert, no change occurs in the write operation when zero documents match your query filter. This is equivalent to passing false to the SetUpsert() method.

The following example performs the following actions:

  • Matches documents where the type is "Oolong"

  • Updates the rating of the matched document to 8

  • Inserts this document if there are no matches to your query filter

filter := bson.D{{"type", "Oolong"}}
update := bson.D{{"$set", bson.D{{"rating", 8}}}}
opts := options.Update().SetUpsert(true)
result, err := coll.UpdateOne(context.TODO(), filter, update, opts)
if err != nil {
panic(err)
}
fmt.Printf("Number of documents updated: %v\n", result.ModifiedCount)
fmt.Printf("Number of documents upserted: %v\n", result.UpsertedCount)

To learn more about the operations mentioned, see the following guides:

To learn more about any of the methods or types mentioned in this guide, see the following API Documentation:

←  Update Arrays in a DocumentBulk Operations →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.