MongoDB Method: db.collection.updateMany()

Summary

Method Namedb.collection.updateMany()
UsageUpdate multiple documents
Group update

Signature

db.collection.updateMany(filter, update, options)

Usage

Update/modify multiple documents of a collection. The documents are select by using a filter, and all the documents matching the criteria are updated by this method.

NOTES

  • If the document(selected by filter) does not already exist, then we have to pass the “upsert” option, if we want to create a new document.
  • updateOne() and updateMany() have same signature. But the difference is-
    • updateOne() will update only one document selected by the filter. If multiple documents matches the filter criteria, then the first one will be updated.
    • updateMany() will update all the documents matching the filter criteria.

Arguments

ParameterDescriptionTypeOptional
filteroptions to filter a documentdocument
updateChanges to apply on the selected documentdocument or pipeline
optionsSome special options for the updatedocumentyes

NOTES

  • The filter options follows the same rules that we use in the db.collection.find().
  • Pass empty document as filter to perform opration on the first document.
  • update” options can accept a document or a pipeline-
    • update document accepts following options-
      • $set – set field value
      • $unset – remove field
      • $rename – rename a field by chaning the filed name
      • $inc – Increase field value(by specific amount)
      • $mul – multiply the field value, with specified amount
      • $setOnInsert – set field and value if new document is being inserted
      • $currentDate – set field value to current date
      • $min – only update the field if its value is minimum(equal or greater) the provided value.
      • $max – only update the field if its value is maximum(equal or less) the provided value.
    • for pipeline options we can provide followig options-
      • $addFields or the alias $set
      • $project or the alias $unset
      • $replaceRoot or the alias $replaceWith

“options” argument parameters

“options” argument accepts a document, an the following options are allowed in the document.

ParameterDescriptionTypeOptional
upsertIf set to true then a new document is created if the method could not find any existing document with the provided criteriabooleanyes
writeConcernMention write convern in a documentdocumentyes
collationDefine the collation to be used for this operationdocumentyes
arrayFiltersArray filter to decide which array element to changearrayyes
hintIndex to be used for this operationdocument or stringyes

Return Value

Return value of this operations is a document, containg the following options-

Return valueCase for the return value
matchedCountNumber of documents that matched the criteria
modifiedCountNumber of changed documents
updatedId_id of the updated document
upsertedCountNumber of created(upserted) document if upsert=true is set and a document is inserted
acknowledgedtrue if writeConcert is provided, or false otherwise

Examples

Here are a few examples of the method usage-

# MongoDB db.collection.updateMany() method demo

# Insert some documents
bigboxcode> db.customer.insertMany([
  {
    "name": "Izabella Conroy",
    "age": 19,
    "phone": "108-679-2154",
    "address": {
      "street": "11 North Vineyard Drive",
      "city": "Minneapolis",
      "state": "Minnesota",
      "postalCode": "19426",
      "country": "US"
    },
    "profileCompletenessScore": 30
  },
  {
    "name": "Lambert Purdy",
    "age": 28,
    "phone": "(610) 489-3633",
    "address": {
      "street": "305 2nd Ave",
      "city": "Collegeville",
      "state": "Minnesota",
      "postalCode": "81007",
      "country": "US"
    },
    "profileCompletenessScore": 40
  },
  {
    "name": "Alisa Parker",
    "age": 72,
    "phone": "768-319-1054",
    "address": {
      "street": "8532 Ingalls Circle",
      "city": "Arvada",
      "state": "CO",
      "postalCode": "80003",
      "country": "CA"
    },
    "profileCompletenessScore": 60
  },
  {
    "name": "Eloise Weber",
    "age": 29,
    "phone": "618-357-2104",
    "address": {
      "street": "632 Belmar Drive",
      "city": "Edmond",
      "state": "OK",
      "postalCode": "73025",
      "country": "CA"
    },
    "profileCompletenessScore": 80
  }
])

output>
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId('65d9ab2b339803ed78702c18'),
    '1': ObjectId('65d9ab2b339803ed78702c19'),
    '2': ObjectId('65d9ab2b339803ed78702c1a'),
    '3': ObjectId('65d9ab2b339803ed78702c1b')
  }
}


# Update based on country and state
# Update phone number and set latitude, longitude
bigboxcode> db.customer.updateMany(
  {"address.country": "US", "address.state": "Minnesota"},
  {$set: {"phone": "(310) 794-7217", "latitude": 34.061106, "longitude": -118.447428}}
)

output>
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 2,
  modifiedCount: 2,
  upsertedCount: 0
}


# Check if age and location exists
# Increase profileCompletenessScore
bigboxcode> db.customer.updateMany(
  {age: {$exists: true}, latitude: {$exists: true}},
  {$inc: {profileCompletenessScore: 20}}
)

output>
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 2,
  modifiedCount: 2,
  upsertedCount: 0
}


# Check by name
# Try to set state, and increase profileCompletenessScore
# Nothing updated as the named does not exist
bigboxcode> db.customer.updateMany(
  {name: "non existing name"},
  {$set: {"address.state": "NY"}, $inc: {profileCompletenessScore: 20}}
)

output>
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 0
}


# Check by name
# set upsert=true
# document created as the named does not exist
bigboxcode> db.customer.updateMany(
  {name: "non existing name"},
  {$set: {"address.state": "NY"}, $inc: {profileCompletenessScore: 20}},
  {upsert: true}
)

output>
{
  acknowledged: true,
  insertedId: ObjectId('65d9b38f3fe0144bdabd2bb2'),
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 1
}


# Check the recently created(upserted) data
bigboxcode> db.customer.findOne(ObjectId('65d9b38f3fe0144bdabd2bb2'))

output>
{
  _id: ObjectId('65d9b38f3fe0144bdabd2bb2'),
  name: 'non existing name',
  address: { state: 'NY' },
  profileCompletenessScore: 20
}

Code Implementations

Here are the usage examples of the MongoDB method in Golang, NodeJS, Java, Python programming languages.

// MongoDB db.collection.updateMany() method examples in Golang

package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

const uri = "mongodb://bigboxuser:bigboxpass@localhost:27017/?maxPoolSize=20&w=majority"

type Customer struct {
	ID                       int     `bson:"_id,omitempty"`
	Name                     string  `bson:"name"`
	Age                      int     `bson:"age"`
	Phone                    string  `bson:"phone,omitempty"`
	Address                  Address `bson:"address,omitempty"`
	ProfileCompletenessScore int     `bson:"profileComplenessScore,omitempty"`
}

type Address struct {
	Street     string `bson:"street,omitempty"`
	City       string `bson:"city,omitempty"`
	State      string `bson:"state,omitempty"`
	PostalCode string `bson:"postalCode,omitempty"`
	Country    string `bson:"country,omitempty"`
}

func main() {
	// Initiate mongo client
	mongoClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
	if err != nil {
		fmt.Println("MongoDB connection error: ", err)
		os.Exit(1)
	}
	defer mongoClient.Disconnect(context.Background())

	// Initiate collection instance
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	customerCollection := mongoClient.Database("bigboxcode").Collection("customer")

	// Insert some documents
	customers := []interface{}{
		Customer{
			Name:  "Izabella Conroy",
			Age:   19,
			Phone: "108-679-2154",
			Address: Address{
				Street:     "11 North Vineyard Drive",
				City:       "Minneapolis",
				State:      "Minnesota",
				PostalCode: "19426",
				Country:    "US",
			},
			ProfileCompletenessScore: 30,
		},
		Customer{
			Name:  "Lambert Purdy",
			Age:   28,
			Phone: "(610) 489-3633",
			Address: Address{
				Street:     "305 2nd Ave",
				City:       "Collegeville",
				State:      "Minnesota",
				PostalCode: "81007",
				Country:    "US",
			},
			ProfileCompletenessScore: 40,
		},
		Customer{
			Name:  "Alisa Parker",
			Age:   72,
			Phone: "768-319-1054",
			Address: Address{
				Street:     "8532 Ingalls Circle",
				City:       "Arvada",
				State:      "CO",
				PostalCode: "80003",
				Country:    "CA",
			},
			ProfileCompletenessScore: 60,
		},
		Customer{
			Name:  "Eloise Weber",
			Age:   29,
			Phone: "618-357-2104",
			Address: Address{
				Street:     "632 Belmar Drive",
				City:       "Edmond",
				State:      "OK",
				PostalCode: "73025",
				Country:    "CA",
			},
			ProfileCompletenessScore: 80,
		},
	}

	insertResult, err := customerCollection.InsertMany(ctx, customers)

	if err != nil {
		fmt.Println("Command: db.customer.insertMany(... 3 documents ) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.insertMany(... 3 documents ) | Result: ", insertResult)

	// Update based on country and state
	// Update phone number and set latitude, longitude
	filter := bson.M{"address.country": "US", "address.state": "Minnesota"}
	update := bson.M{"$set": bson.M{"phone": "(310) 794-7217", "latitude": 34.061106, "longitude": -118.447428}}

	// Perform updateMany operation
	updateResult, err := customerCollection.UpdateMany(ctx, filter, update)
	if err != nil {
		fmt.Println("Command: db.customer.updateMany(......find by country and state, ......update phone and set lat, lng) | Error: ", err)
	}

	fmt.Println("Command: db.customer.updateMany(......find by country and state, ......update phone and set lat, lng) | Result: ", updateResult)

	// Check if age and location exists
	// Increase profileCompletenessScore
	filter = bson.M{"age": bson.M{"$exists": true}, "latitude": bson.M{"$exists": true}}
	update = bson.M{"$inc": bson.M{"profileCompletenessScore": 7}}
	updateResult, err = customerCollection.UpdateMany(ctx, filter, update)
	if err != nil {
		fmt.Println("Command: db.customer.updateMany(......find by age and latitude, ......increase profile completeness) | Error: ", err)
	}

	fmt.Println("Command: db.customer.updateMany(......find by age and latitude, ......increase profile completeness) | Result: ", updateResult)

	// Check by name
	// Try to set state, and increase profileCompletenessScore
	// Nothing updated as the named does not exist
	filter = bson.M{"name": "non existing name"}
	update = bson.M{"$set": bson.M{"address.state": "NY"}, "$inc": bson.M{"profileCompletenessScore": 20}}
	updateResult, err = customerCollection.UpdateMany(ctx, filter, update)
	if err != nil {
		fmt.Println("Command: db.customer.updateOne(......find by name, ......update state and score) | Error: ", err)
	}

	fmt.Println("Command: db.customer.updateOne(......find by name, ......update  state and score) | Result: ", updateResult)

	// Check by name
	// set upsert=true
	// document created as the named does not exist
	filter = bson.M{"name": "non existing name"}
	update = bson.M{"$set": bson.M{"address.state": "NY"}, "$inc": bson.M{"profileCompletenessScore": 20}}
	options := options.Update().SetUpsert(true)
	updateResult, err = customerCollection.UpdateMany(ctx, filter, update, options)
	if err != nil {
		fmt.Println("Command: db.customer.updateOne(......find by name, ......update state and score, provide upsert option) | Error: ", err)
	}

	fmt.Println("Command: db.customer.updateOne(......find by name, ......update state and score, provide upsert option) | Result: ", updateResult)

}

Output:

Command: db.customer.insertMany(... 3 documents ) | Result:  &{[ObjectID("65daf830a2e8007a90d15fe8") ObjectID("65daf830a2e8007a90d15fe9") ObjectID("65daf830a2e8007a90d15fea") ObjectID("65daf830a2e8007a90d15feb")]}

Command: db.customer.updateMany(......find by country and state, ......update phone and set lat, lng) | Result:  &{2 2 0 <nil>}

Command: db.customer.updateMany(......find by age and latitude, ......increase profile completeness) | Result:  &{2 2 0 <nil>}

Command: db.customer.updateOne(......find by name, ......update  state and score) | Result:  &{0 0 0 <nil>}

Command: db.customer.updateOne(......find by name, ......update state and score, provide upsert option) | Result:  &{0 0 1 ObjectID("65daf8300b56494d058d5743")}

NOTES

  • Use the “UpdateMany()” method from “mongo-go-driver
  • Signature of the method-
    • func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*UpdateResult, error)
  • Definition of UpdateOptions

    type UpdateOptions struct {
        ArrayFilters *ArrayFilters
        BypassDocumentValidation *bool
        Collation *Collation
        Comment interface{}
        Hint interface{}
        Upsert *bool
        Let interface{}
    }
  • Definition of UpdateResult

    type UpdateResult struct {
        MatchedCount  int64
        ModifiedCount int64
        UpsertedCount int64
        UpsertedID    interface{}
    }
// db.collection.updateMany() method example in NodeJS

import { MongoClient } from "mongodb";

async function main() {
  // Define MongoDB connection URI
  const uri = "mongodb://bigboxuser:bigboxpass@127.0.0.1:27017";

  // Create a client
  const mongo = new MongoClient(uri);

  await mongo.connect();

  const database = mongo.db("bigboxcode");
  const customerCollection = database.collection("customer");

  try {
    // Insert some documents
    let commandResult = await customerCollection.insertMany([
      {
        name: "Izabella Conroy",
        age: 19,
        phone: "108-679-2154",
        address: {
          street: "11 North Vineyard Drive",
          city: "Minneapolis",
          state: "Minnesota",
          postalCode: "19426",
          country: "US",
        },
        profileCompletenessScore: 30,
      },
      {
        name: "Lambert Purdy",
        age: 28,
        phone: "(610) 489-3633",
        address: {
          street: "305 2nd Ave",
          city: "Collegeville",
          state: "Minnesota",
          postalCode: "81007",
          country: "US",
        },
        profileCompletenessScore: 40,
      },
      {
        name: "Alisa Parker",
        age: 72,
        phone: "768-319-1054",
        address: {
          street: "8532 Ingalls Circle",
          city: "Arvada",
          state: "CO",
          postalCode: "80003",
          country: "CA",
        },
        profileCompletenessScore: 60,
      },
      {
        name: "Eloise Weber",
        age: 29,
        phone: "618-357-2104",
        address: {
          street: "632 Belmar Drive",
          city: "Edmond",
          state: "OK",
          postalCode: "73025",
          country: "CA",
        },
        profileCompletenessScore: 80,
      },
    ]);

    console.log(
      "Command: db.customer.insertMany(... 3 documents ) | Result: ",
      commandResult
    );

    // Update based on country and state
    commandResult = await customerCollection.updateMany(
      { "address.country": "US", "address.state": "Minnesota" },
      {
        $set: {
          phone: "(310) 794-7217",
          latitude: 34.061106,
          longitude: -118.447428,
        },
      }
    );

    console.log(
      "Command: db.customer.updateMany(......find by country and state, ......update phone and set lat, lng) | Result:",
      commandResult
    );

    // Increase profileCompletenessScore where age and location exist
    commandResult = await customerCollection.updateMany(
      { age: { $exists: true }, latitude: { $exists: true } },
      { $inc: { profileCompletenessScore: 20 } }
    );

    console.log(
      "Command: db.customer.updateMany(......find by age and latitude, ......increase profile completeness) | Result:",
      commandResult
    );

    // Try to update based on name (non-existing name)
    commandResult = await customerCollection.updateMany(
      { name: "non existing name" },
      {
        $set: { "address.state": "NY" },
        $inc: { profileCompletenessScore: 20 },
      }
    );

    console.log(
      "Command: db.customer.updateOne(......find by name, ......update  state and score) | Result:",
      commandResult
    );

    // Upsert a document with the specified name
    commandResult = await customerCollection.updateMany(
      { name: "non existing name" },
      {
        $set: { "address.state": "NY" },
        $inc: { profileCompletenessScore: 20 },
      },
      { upsert: true }
    );

    console.log(
      "Command: db.customer.updateOne(......find by name, ......update state and score, provide upsert option) | Result:",
      commandResult
    );
  } finally {
    await mongo.close();
  }
}

await main().catch(console.error);

process.exit(0);

Output:

Command: db.customer.insertMany(... 3 documents ) | Result:  {
  acknowledged: true,
  insertedCount: 4,
  insertedIds: {
    '0': new ObjectId('65ddaa6821bbe3589769d39f'),
    '1': new ObjectId('65ddaa6821bbe3589769d3a0'),
    '2': new ObjectId('65ddaa6821bbe3589769d3a1'),
    '3': new ObjectId('65ddaa6821bbe3589769d3a2')
  }
}

Command: db.customer.updateMany(......find by country and state, ......update phone and set lat, lng) | Result: {
  acknowledged: true,
  modifiedCount: 2,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 2
}

Command: db.customer.updateMany(......find by age and latitude, ......increase profile completeness) | Result: {
  acknowledged: true,
  modifiedCount: 2,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 2
}

Command: db.customer.updateOne(......find by name, ......update  state and score) | Result: {
  acknowledged: true,
  modifiedCount: 0,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 0
}

Command: db.customer.updateOne(......find by name, ......update state and score, provide upsert option) | Result: {
  acknowledged: true,
  modifiedCount: 0,
  upsertedId: new ObjectId('65ddaa68d488afc713e745a1'),
  upsertedCount: 1,
  matchedCount: 0
}

NOTES

  • Use NodeJS “updateMany()” method from the package “mongodb“.
  • Method signatures are-
    • updateMany(filter: Filter<TSchema>, update: UpdateFilter<TSchema>, options?: UpdateOptions): Promise<UpdateResult<TSchema>>
# db.collection.updateMany() method example in Python

from pymongo import MongoClient, WriteConcern
import re
from datetime import datetime

# Create MongoDB client
mongo_client = MongoClient("mongodb://bigboxuser:bigboxpass@127.0.0.1:27017/")

# Select database and collection
mongo_database = mongo_client.bigboxcode
customer_collection = mongo_database.customer

try:
    # Insert some documents
    command_result = customer_collection.insert_many([
        {
            "name": "Izabella Conroy",
            "age": 19,
            "phone": "108-679-2154",
            "address": {
                "street": "11 North Vineyard Drive",
                "city": "Minneapolis",
                "state": "Minnesota",
                "postalCode": "19426",
                "country": "US",
            },
            "profileCompletenessScore": 30,
        },
        {
            "name": "Lambert Purdy",
            "age": 28,
            "phone": "(610) 489-3633",
            "address": {
                "street": "305 2nd Ave",
                "city": "Collegeville",
                "state": "Minnesota",
                "postalCode": "81007",
                "country": "US",
            },
            "profileCompletenessScore": 40,
        },
        {
            "name": "Alisa Parker",
            "age": 72,
            "phone": "768-319-1054",
            "address": {
                "street": "8532 Ingalls Circle",
                "city": "Arvada",
                "state": "CO",
                "postalCode": "80003",
                "country": "CA",
            },
            "profileCompletenessScore": 60,
        },
        {
            "name": "Eloise Weber",
            "age": 29,
            "phone": "618-357-2104",
            "address": {
                "street": "632 Belmar Drive",
                "city": "Edmond",
                "state": "OK",
                "postalCode": "73025",
                "country": "CA",
            },
            "profileCompletenessScore": 80,
        },
    ])

    print("Command: db.customer.insert_many(... 3 documents ) | Result:", command_result)

    # Update based on country and state
    command_result = customer_collection.update_many(
        {"address.country": "US", "address.state": "Minnesota"},
        {"$set": {"phone": "(310) 794-7217", "latitude": 34.061106, "longitude": -118.447428}}
    )

    print("Command: db.customer.update_many(......find by country and state, ......update phone and set lat, lng) | Result:", command_result)

    # Increase profileCompletenessScore where age and location exist
    command_result = customer_collection.update_many(
        {"age": {"$exists": True}, "latitude": {"$exists": True}},
        {"$inc": {"profileCompletenessScore": 20}}
    )

    print("Command: db.customer.update_many(......find by age and latitude, ......increase profile completeness) | Result:", command_result)

    # Try to update based on name (non-existing name)
    command_result = customer_collection.update_many(
        {"name": "non existing name"},
        {"$set": {"address.state": "NY"}, "$inc": {"profileCompletenessScore": 20}}
    )

    print("Command: db.customer.update_one(......find by name, ......update state and score) | Result:", command_result)

    # Upsert a document with the specified name
    command_result = customer_collection.update_many(
        {"name": "non existing name"},
        {"$set": {"address.state": "NY"}, "$inc": {"profileCompletenessScore": 20}},
        upsert=True
    )

    print("Command: db.customer.update_one(......find by name, ......update state and score, provide upsert option) | Result:", command_result)

finally:
    mongo_client.close()

Output:

Command: db.customer.insert_many(... 3 documents ) | Result: InsertManyResult([ObjectId('65ddad9558a2675e85832642'), ObjectId('65ddad9558a2675e85832643'), ObjectId('65ddad9558a2675e85832644'), ObjectId('65ddad9558a2675e85832645')], acknowledged=True)
Command: db.customer.update_many(......find by country and state, ......update phone and set lat, lng) | Result: UpdateResult({'n': 2, 'nModified': 2, 'ok': 1.0, 'updatedExisting': True}, acknowledged=True)
Command: db.customer.update_many(......find by age and latitude, ......increase profile completeness) | Result: UpdateResult({'n': 2, 'nModified': 2, 'ok': 1.0, 'updatedExisting': True}, acknowledged=True)
Command: db.customer.update_one(......find by name, ......update state and score) | Result: UpdateResult({'n': 0, 'nModified': 0, 'ok': 1.0, 'updatedExisting': False}, acknowledged=True)
Command: db.customer.update_one(......find by name, ......update state and score, provide upsert option) | Result: UpdateResult({'n': 1, 'upserted': ObjectId('65ddad95d488afc713e74664'), 'nModified': 0, 'ok': 1.0, 'updatedExisting': False}, acknowledged=True)  

NOTES

  • Use method “update_many” from redis-py.
  • Signature of the method is –
    • def update_many(
              self,
              filter: Mapping[str, Any],
              update: Union[Mapping[str, Any], _Pipeline],
              upsert: bool = False,
              bypass_document_validation: bool = False,
              collation: Optional[_CollationIn] = None,
              array_filters: Optional[Sequence[Mapping[str, Any]]] = None,
              hint: Optional[_IndexKeyHint] = None,
              session: Optional[ClientSession] = None,
              let: Optional[Mapping[str, Any]] = None,
              comment: Optional[Any] = None,
          ) -> UpdateResult
// db.collection.updateMany() method example in Java

import com.mongodb.client.*;
import com.mongodb.client.result.InsertManyResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.bson.types.ObjectId;

import java.util.List;

public class UpdateMany {
    public static void main(String[] args) {
        String uri = "mongodb://bigboxuser:bigboxpass@localhost:27017/";

        try (MongoClient mongoClient = MongoClients.create(uri)) {
            MongoDatabase database = mongoClient.getDatabase("bigboxcode");
            MongoCollection<Document> customerCollection = database.getCollection("customer");

            // Insert some documents
            InsertManyResult insertResult = customerCollection.insertMany(List.of(
                    new Document("name", "Izabella Conroy")
                            .append("age", 19)
                            .append("phone", "108-679-2154")
                            .append("address", new Document()
                                    .append("street", "11 North Vineyard Drive")
                                    .append("city", "Minneapolis")
                                    .append("state", "Minnesota")
                                    .append("postalCode", "19426")
                                    .append("country", "US"))
                            .append("profileCompletenessScore", 30),
                    new Document("name", "Lambert Purdy")
                            .append("age", 28)
                            .append("phone", "(610) 489-3633")
                            .append("address", new Document()
                                    .append("street", "305 2nd Ave")
                                    .append("city", "Collegeville")
                                    .append("state", "Minnesota")
                                    .append("postalCode", "81007")
                                    .append("country", "US"))
                            .append("profileCompletenessScore", 40),
                    new Document("name", "Alisa Parker")
                            .append("age", 72)
                            .append("phone", "768-319-1054")
                            .append("address", new Document()
                                    .append("street", "8532 Ingalls Circle")
                                    .append("city", "Arvada")
                                    .append("state", "CO")
                                    .append("postalCode", "80003")
                                    .append("country", "CA"))
                            .append("profileCompletenessScore", 60),
                    new Document("name", "Eloise Weber")
                            .append("age", 29)
                            .append("phone", "618-357-2104")
                            .append("address", new Document()
                                    .append("street", "632 Belmar Drive")
                                    .append("city", "Edmond")
                                    .append("state", "OK")
                                    .append("postalCode", "73025")
                                    .append("country", "CA"))
                            .append("profileCompletenessScore", 80)
            ));

            System.out.println("Command: db.customer.insertMany(... 3 documents ) | Result: " + insertResult);

            // Update based on country and state
            UpdateResult updateResult = customerCollection.updateMany(
                    new Document("address.country", "US").append("address.state", "Minnesota"),
                    new Document("$set", new Document()
                            .append("phone", "(310) 794-7217")
                            .append("latitude", 34.061106)
                            .append("longitude", -118.447428))
            );

            System.out.println("Command: db.customer.updateMany(......find by country and state, ......update phone and set lat, lng) | Result:" + updateResult);

            // Increase profileCompletenessScore where age and location exist
            updateResult = customerCollection.updateMany(
                    new Document("age", new Document("$exists", true)).append("latitude", new Document("$exists", true)),
                    new Document("$inc", new Document("profileCompletenessScore", 20))
            );

            System.out.println("Command: db.customer.updateMany(......find by age and latitude, ......increase profile completeness) | Result:" + updateResult);

            // Try to update based on name (non-existing name)
            updateResult = customerCollection.updateMany(
                    new Document("name", "non existing name"),
                    new Document("$set", new Document("address.state", "NY").append("inc", new Document("profileCompletenessScore", 20)))
            );

            System.out.println("Command: db.customer.updateOne(......find by name, ......update  state and score) | Result:" + updateResult);

            // Upsert a document with the specified name
            updateResult = customerCollection.updateMany(
                    new Document("name", "non existing name"),
                    new Document("$set", new Document("address.state", "NY").append("inc", new Document("profileCompletenessScore", 20))),
                    new com.mongodb.client.model.UpdateOptions().upsert(true)
            );

            System.out.println("Command: db.customer.updateOne(......find by name, ......update state and score, provide upsert option) | Result:" + updateResult);

            mongoClient.close();

        }
    }
}

Output:

Command: db.customer.insertMany(... 3 documents ) | Result: AcknowledgedInsertManyResult{insertedIds={0=BsonObjectId{value=65ddc53858ef4e600b745e50}, 1=BsonObjectId{value=65ddc53858ef4e600b745e51}, 2=BsonObjectId{value=65ddc53858ef4e600b745e52}, 3=BsonObjectId{value=65ddc53858ef4e600b745e53}}}

Command: db.customer.updateMany(......find by country and state, ......update phone and set lat, lng) | Result:AcknowledgedUpdateResult{matchedCount=2, modifiedCount=2, upsertedId=null}

Command: db.customer.updateMany(......find by age and latitude, ......increase profile completeness) | Result:AcknowledgedUpdateResult{matchedCount=2, modifiedCount=2, upsertedId=null}

Command: db.customer.updateOne(......find by name, ......update  state and score) | Result:AcknowledgedUpdateResult{matchedCount=0, modifiedCount=0, upsertedId=null}

Command: db.customer.updateOne(......find by name, ......update state and score, provide upsert option) | Result:AcknowledgedUpdateResult{matchedCount=0, modifiedCount=0, upsertedId=BsonObjectId{value=65ddc538d488afc713e74b8e}}

NOTES

  • Use the method “updateMany()” from MongoCollection.
  • Signatures of the method are-
    • UpdateResult updateMany(Bson filter, Bson update)
    • UpdateResult updateMany(Bson filter, Bson update, UpdateOptions updateOptions)
    • UpdateResult updateMany(ClientSession clientSession, Bson filter, Bson update)
    • UpdateResult updateMany(ClientSession clientSession, Bson filter, Bson update, UpdateOptions updateOptions)
    • UpdateResult updateMany(Bson filter, List<? extends Bson> update)
    • UpdateResult updateMany(Bson filter, List<? extends Bson> update, UpdateOptions updateOptions)
    • UpdateResult updateMany(ClientSession clientSession, Bson filter, List<? extends Bson> update)
    • UpdateResult updateMany(ClientSession clientSession, Bson filter, List<? extends Bson> update, UpdateOptions updateOptions)

Source Code

Use the following links to get the source code used in this article-

Related Methods

CommandDetails
db.collection.updateOne() Method Details
db.collection.insertMany() Method Details
db.collection.findOne() Method Details

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.