Docs Menu

Update Arrays in a Document

On this page

  • Overview
  • Sample Data
  • Specify Array Elements
  • First Array Element
  • Multiple Array Elements
  • All Array Elements
  • Additional Information
  • API Documentation

In this guide, you can learn how to update array elements in a document.

To update elements in an array, perform the following actions:

  • Provide an update document that specifies the update.
  • Specify which array elements to update.
  • Perform the update using an update operation with these specifications.

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

coll := client.Database("tea").Collection("quantity")
docs := []interface{}{
bson.D{{"type", "Masala"}, {"qty", bson.A{15, 12, 18}}},
}
result, err := coll.InsertMany(context.TODO(), docs)
if err != nil {
panic(err)
}
fmt.Printf("%d documents inserted with IDs:\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.

The following examples use the FindOneAndUpdate() method to retrieve and update a document and to return the state of the document after the update occurs. If you want to update multiple documents with an array field, use the UpdateMany() method.

Note

Each example truncates the ObjectID value because the driver generates them uniquely.

To specify which array elements to update, use a positional operator. Positional operators can specify the first, multiple, or all array elements to update.

To specify array elements with a positional operator, use dot notation. Dot notation is a property access syntax for navigating array elements and fields of an embedded document.

To update the first array element that matches your query filter, use the positional $ operator. The query filter must be for the array field.

This example performs the following actions:

  • Matches array elements in qty where the value is greater than 10.
  • Decrements the first array value matched by 5.
filter := bson.D{{"qty", bson.D{{"$gt", 10}}}}
update := bson.D{{"$inc", bson.D{{"qty.$", -5}}}}
opts := options.FindOneAndUpdate().SetReturnDocument(options.After)
var updatedDoc bson.D
err := coll.FindOneAndUpdate(context.TODO(), filter, update, opts).Decode(&updatedDoc)
if err != nil {
panic(err)
}
fmt.Println(updatedDoc)
Note

The query filter matches the values 15 and 12. Since 15 is the first element matched, it is updated. If you want to update both matched values, see Multiple Array Elements.

To update multiple array elements that match your query filter, use the filtered positional $[<identifier>] operator. You must include an array filter in your update operation to specify which array elements to update.

The <identifier> is the name you use within your array filter. This value must begin with a lowercase letter and only contain alphanumeric characters.

This example performs the following actions:

  • Creates an array filter with an identifier called smaller to match elements less than 18.
  • Applies the array filter using the SetArrayFilters() method.
  • Increments every matched element by 7.
identifier := []interface{}{bson.D{{"smaller", bson.D{{"$lt", 18}}}}}
update := bson.D{{"$inc", bson.D{{"qty.$[smaller]", 7}}}}
opts := options.FindOneAndUpdate().SetArrayFilters(options.ArrayFilters{Filters: identifier}).SetReturnDocument(options.After)
var updatedDoc bson.D
err := coll.FindOneAndUpdate(context.TODO(), bson.D{}, update, opts).Decode(&updatedDoc)
if err != nil {
panic(err)
}
fmt.Println(updatedDoc)

To update all the array elements, use the all positional $[] operator.

Note

If you specify a query filter for the array field, the positional $[] operator ignores the query filter and updates all the array elements.

This example multiplies every array element in qty by 2:

update := bson.D{{"$mul", bson.D{{"qty.$[]", 2}}}}
opts := options.FindOneAndUpdate().SetReturnDocument(options.After)
var updatedDoc bson.D
err := coll.FindOneAndUpdate(context.TODO(), bson.D{}, update, opts).Decode(&updatedDoc)
if err != nil {
panic(err)
}
fmt.Println(updatedDoc)

To learn more about the operations discussed in this guide, see the following guides:

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

←  Change a DocumentInsert or Update in a Single Operation →
Give Feedback
© 2022 MongoDB, Inc.

About

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