MongoDB Method: db.collection.updateOne()

Summary

Method Namedb.collection.updateOne()
UsageUpdate single document
Group update

Signature

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

Usage

Update/modify a single existing document in a collection. The selection of the document is done by using some filters.

NOTES

  • If the document does not already exist, then we have pass “upsert” option, if we want to create a new document.

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.updateOne() 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": "Pueblo West",
      "state": "CO",
      "postalCode": "81007"
    }
  },
  {
    "name": "Alisa Parker",
    "age": 72,
    "phone": "768-319-1054",
    "address": {
      "street": "8532 Ingalls Circle",
      "city": "Arvada",
      "state": "CO",
      "postalCode": "80003"
    }
  },
  {
    "name": "Eloise Weber",
    "age": 29,
    "phone": "618-357-2104",
    "address": {
      "street": "632 Belmar Drive",
      "city": "Edmond",
      "state": "OK",
      "postalCode": "73025"
    }
  }
])


output>
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId('65d3219582913eadf267bbc2'),
    '1': ObjectId('65d3219582913eadf267bbc3'),
    '2': ObjectId('65d3219582913eadf267bbc4')
  }
}

# Select by id and change name, age and city
bigboxcode> db.customer.updateOne(
  { _id:  ObjectId('65d3219582913eadf267bbc2') },
  { $set: {"name": "My Name Changed 9", "age": 100, "address.city": "city88" } }
)

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


# Check the changed document
bigboxcode> db.customer.find(ObjectId('65d3219582913eadf267bbc2'))

output>
[
  {
    _id: ObjectId('65d3219582913eadf267bbc2'),
    name: 'My Name Changed 9',
    age: 100,
    phone: '108-679-2154',
    address: {
      street: '11 North Vineyard Drive',
      city: 'city88',
      state: 'CO',
      postalCode: '81007'
    }
  }
]


# Select by id.
# Change state
# Increase age by 7
bigboxcode> db.customer.updateOne(
  { _id:  ObjectId('65d3219582913eadf267bbc2') },
  { $set: {"address.state": "ABC" }, $inc: {"age": 7} }
)

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


# Check changed document
bigboxcode> db.customer.find(ObjectId('65d3219582913eadf267bbc2'))

output:
[
  {
    _id: ObjectId('65d3219582913eadf267bbc2'),
    name: 'My Name Changed 9',
    age: 107,
    phone: '108-679-2154',
    address: {
      street: '11 North Vineyard Drive',
      city: 'city88',
      state: 'ABC',
      postalCode: '81007'
    },
    state: 'ABC'
  }
]


# Filter by name
# Chagne age
bigboxcode> db.customer.updateOne(
  { "name":  "Alisa Parker" },
  { $set: {"age": 10 } }
)

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


# Filter by non existing name
# Try to change age
# Nothing changed
bigboxcode> db.customer.updateOne(
  { "name":  "Non Existing Name" },
  { $set: {"age": 100 } }
)

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


# Filter by non existing name
# Update age
# provide upsert=2
# new document created
bigboxcode> db.customer.updateOne(
 { "name":  "Non Existing Name" },
 { $set: {"age": 100 } },
 { upsert: true }
)

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


# Check upserted document
bigboxcode> db.customer.find({ "name":  "Non Existing Name" })

output:
[
  {
    _id: ObjectId('65d33f5c14d002566c67b4eb'),
    name: 'Non Existing Name',
    age: 100
  }
]

Code Implementations

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

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

package main

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

	"go.mongodb.org/mongo-driver/bson"
	_ "go.mongodb.org/mongo-driver/bson/primitive"
	"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"`
}

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:       "Pueblo West",
				State:      "CO",
				PostalCode: "81007",
			},
		},
		Customer{
			Name:  "Alisa Parker",
			Age:   72,
			Phone: "768-319-1054",
			Address: Address{
				Street:     "8532 Ingalls Circle",
				City:       "Arvada",
				State:      "CO",
				PostalCode: "80003",
			},
		},
		Customer{
			Name:  "Eloise Weber",
			Age:   29,
			Phone: "618-357-2104",
			Address: Address{
				Street:     "632 Belmar Drive",
				City:       "Edmond",
				State:      "OK",
				PostalCode: "73025",
			},
		},
	}

	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)

	//  Select by id and change name, age and city
	objectId := insertResult.InsertedIDs[0] // primitive.ObjectIDFromHex("65d3219582913eadf267bbc2")
	filter := bson.M{"_id": objectId}
	update := bson.M{"$set": bson.M{"name": "My Name Changed 9", "age": 100, "address.city": "city88"}}

	// Perform updateOne operation
	updateResult, err := customerCollection.UpdateOne(ctx, filter, update)
	if err != nil {
		fmt.Println("Command: db.customer.updateOne(......find by id, ......update name, age, city) | Error: ", err)
	}

	fmt.Println("Command: db.customer.updateOne(......find by id, ......update name, age, city) | Result: ", updateResult)

	// Check the changed document
	var customer bson.M
	err = customerCollection.FindOne(ctx, filter).Decode(&customer)
	if err != nil {
		fmt.Println("db.customer.find(ObjectId('65d3219582913eadf267bbc2')) | Error: ", err)
	}

	fmt.Println("db.customer.find(ObjectId('65d3219582913eadf267bbc2')) | Result: ", customer)

	// Update document with specified ObjectId, changing state and increasing age
	update = bson.M{"$set": bson.M{"address.state": "ABC"}, "$inc": bson.M{"age": 7}}
	updateResult, err = customerCollection.UpdateOne(ctx, filter, update)
	if err != nil {
		fmt.Println("Command: db.customer.updateOne(......find by id, ......update state, age) | Error: ", err)
	}

	fmt.Println("Command: db.customer.updateOne(......find by id, ......update state, age) | Result: ", updateResult)

	// Update document by filtering with name
	filter = bson.M{"name": "Alisa Parker"}
	update = bson.M{"$set": bson.M{"age": 10}}
	updateResult, err = customerCollection.UpdateOne(ctx, filter, update)
	if err != nil {
		fmt.Println("Command: db.customer.updateOne(......find by name, ......update age) | Error: ", err)
	}

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

	// Attempt to update a non-existing document, no document matched, nothing changed
	filterByNonExistingName := bson.M{"name": "Non Existing Name"}
	updateNonExisting := bson.M{"$set": bson.M{"age": 100}}
	updateResult, err = customerCollection.UpdateOne(ctx, filterByNonExistingName, updateNonExisting)
	if err != nil {
		fmt.Println("Command: db.customer.updateOne(......find by non existing name, ......update age) | Error: ", err)
	}

	fmt.Println("Command: db.customer.updateOne(......find by non existing name, ......update age) | Result: ", updateResult)

	// Attempt to update a non-existing document with upsert, creating a new document
	opts := options.Update().SetUpsert(true)
	updateResult, err = customerCollection.UpdateOne(ctx, filterByNonExistingName, updateNonExisting, opts)
	if err != nil {
		fmt.Println("Command: db.customer.updateOne(......find by non existing name, ......update age, .....provide upsert option) | Error: ", err)
	}

	fmt.Println("Command: db.customer.updateOne(......find by non existing name, ......update age, .....provide upsert option) | Result: ", updateResult)

	// Check the upserted document
	var nonExistingCustomer bson.M
	err = customerCollection.FindOne(ctx, filterByNonExistingName).Decode(&nonExistingCustomer)
	if err != nil {
		fmt.Println("Command: db.customer.find({ \"name\":  \"Non Existing Name\" }) | Error: ", err)
	}

	fmt.Println("Command: db.customer.find({ \"name\":  \"Non Existing Name\" }) | Result: ", nonExistingCustomer)

}

Output:

Command: db.customer.insertMany(... 3 documents ) | Result:  &{[ObjectID("65d450a63241dfe2b7d5cb17") ObjectID("65d450a63241dfe2b7d5cb18") ObjectID("65d450a63241dfe2b7d5cb19")]}

Command: db.customer.updateOne(......find by id, ......update name, age, city) | Result:  &{1 1 0 <nil>}

db.customer.find(ObjectId('65d3219582913eadf267bbc2')) | Result:  map[_id:ObjectID("65d450a63241dfe2b7d5cb17") address:map[city:city88 postalCode:81007 state:CO street:11 North Vineyard Drive] age:100 name:My Name Changed 9 phone:108-679-2154]

Command: db.customer.updateOne(......find by id, ......update state, age) | Result:  &{1 1 0 <nil>}

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

Command: db.customer.updateOne(......find by non existing name, ......update age) | Result:  &{0 0 0 <nil>}

Command: db.customer.updateOne(......find by non existing name, ......update age, .....provide upsert option) | Result:  &{0 0 1 ObjectID("65d450a614d002566c67ef10")}

Command: db.customer.find({ "name":  "Non Existing Name" }) | Result:  map[_id:ObjectID("65d450a614d002566c67ef10") age:100 name:Non Existing Name]

NOTES

  • Use the “UpdateOne()” method from “mongo-go-driver
  • Signature of the method-
    • func (coll *Collection) UpdateOne(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.updateOne() method example in NodeJS

import { MongoClient } from "mongodb";

// 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");

// Insert some documents
let commandResult = await customerCollection.insertMany([
  {
    name: "Izabella Conroy",
    age: 19,
    phone: "108-679-2154",
    address: {
      street: "11 North Vineyard Drive",
      city: "Pueblo West",
      state: "CO",
      postalCode: "81007",
    },
  },
  {
    name: "Alisa Parker",
    age: 72,
    phone: "768-319-1054",
    address: {
      street: "8532 Ingalls Circle",
      city: "Arvada",
      state: "CO",
      postalCode: "80003",
    },
  },
  {
    name: "Eloise Weber",
    age: 29,
    phone: "618-357-2104",
    address: {
      street: "632 Belmar Drive",
      city: "Edmond",
      state: "OK",
      postalCode: "73025",
    },
  },
]);

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

// Check the changed document
const objId = commandResult.insertedIds[0];

commandResult = await customerCollection.findOne({
  _id: objId,
});

console.log("Command: db.customer.find(objId) | Result: ", commandResult);

// Select by id and change name, age, and city
commandResult = await customerCollection.updateOne(
  { _id: objId },
  { $set: { name: "My Name Changed 9", age: 100, "address.city": "city88" } }
);

console.log(
  "Command: db.customer.updateOne(......find by id, ......update name, age, city) | Result: ",
  commandResult
);

// Select by id. Change state. Increase age by 7
commandResult = await customerCollection.updateOne(
  { _id: objId },
  { $set: { "address.state": "ABC" }, $inc: { age: 7 } }
);

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

// Filter by name. Change age
commandResult = await customerCollection.updateOne(
  { name: "Alisa Parker" },
  { $set: { age: 10 } }
);

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

// Filter by non-existing name. Try to change age
commandResult = await customerCollection.updateOne(
  { name: "Non Existing Name" },
  { $set: { age: 100 } }
);

console.log(
  "Command: db.customer.updateOne(......find by non existing name, ......update age) | Result: ",
  commandResult
);

// Filter by non-existing name. Update age. Provide upsert=true. New document created
commandResult = await customerCollection.updateOne(
  { name: "Non Existing Name" },
  { $set: { age: 100 } },
  { upsert: true }
);

console.log(
  "Command: db.customer.updateOne(......find by non existing name, ......update age, .....provide upsert option) | Result: ",
  commandResult
);

// Check upserted document
commandResult = await customerCollection.findOne({ name: "Non Existing Name" });
console.log(
  'Command: db.customer.find({ "name":  "Non Existing Name" }) | Result: ',
  commandResult
);

// Close connection
await mongo.close();

process.exit(0);

Output:

Command: db.customer.insertMany(... 3 documents ) | Result:  {
  acknowledged: true,
  insertedCount: 3,
  insertedIds: {
    '0': new ObjectId('65d5d593b5e1c7578a87a327'),
    '1': new ObjectId('65d5d593b5e1c7578a87a328'),
    '2': new ObjectId('65d5d593b5e1c7578a87a329')
  }
}

Command: db.customer.find(objId) | Result:  {
  _id: new ObjectId('65d5d593b5e1c7578a87a327'),
  name: 'Izabella Conroy',
  age: 19,
  phone: '108-679-2154',
  address: {
    street: '11 North Vineyard Drive',
    city: 'Pueblo West',
    state: 'CO',
    postalCode: '81007'
  }
}

Command: db.customer.updateOne(......find by id, ......update name, age, city) | Result:  {
  acknowledged: true,
  modifiedCount: 1,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 1
}

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

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

Command: db.customer.updateOne(......find by non existing name, ......update age) | Result:  {
  acknowledged: true,
  modifiedCount: 0,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 1
}

Command: db.customer.updateOne(......find by non existing name, ......update age, .....provide upsert option) | Result:  {
  acknowledged: true,
  modifiedCount: 0,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 1
}

Command: db.customer.find({ "name":  "Non Existing Name" }) | Result:  {
  _id: new ObjectId('65d5d4b6cd703a462ed374ba'),
  name: 'Non Existing Name',
  age: 100
}

NOTES

  • Use NodeJS “updateOne()” method from the package “mongodb“.
  • Method signatures are-
    • updateOne(filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Partial<TSchema>, options?: UpdateOptions): Promise<UpdateResult<TSchema>>
# db.collection.updateOne() 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


# 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": "Pueblo West",
                "state": "CO",
                "postalCode": "81007",
            },
        },
        {
            "name": "Alisa Parker",
            "age": 72,
            "phone": "768-319-1054",
            "address": {
                "street": "8532 Ingalls Circle",
                "city": "Arvada",
                "state": "CO",
                "postalCode": "80003",
            },
        },
        {
            "name": "Eloise Weber",
            "age": 29,
            "phone": "618-357-2104",
            "address": {
                "street": "632 Belmar Drive",
                "city": "Edmond",
                "state": "OK",
                "postalCode": "73025",
            },
        },
    ]
)

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

# Check the changed document
obj_id = command_result.inserted_ids[0]

command_result = customer_collection.find_one(
    {
        "_id": obj_id,
    }
)

print("Command: db.customer.find(obj_id) | Result: ", command_result)

# Select by id and change name, age, and city
command_result = customer_collection.update_one(
    {"_id": obj_id},
    {"$set": {"name": "My Name Changed 9", "age": 100, "address.city": "city88"}},
)

print(
    "Command: db.customer.updateOne(......find by id, ......update name, age, city) | Result: ",
    command_result.raw_result,
)

# Select by id. Change state. Increase age by 7
command_result = customer_collection.update_one(
    {"_id": obj_id}, {"$set": {"address.state": "ABC"}, "$inc": {"age": 7}}
)

print(
    "Command: db.customer.updateOne(......find by id, ......update state, age) | Result: ",
    command_result.raw_result,
)

# Filter by name. Change age
command_result = customer_collection.update_one(
    {"name": "Alisa Parker"}, {"$set": {"age": 10}}
)

print(
    "Command: db.customer.updateOne(......find by name, ......update age) | Result: ",
    command_result.raw_result,
)

# Filter by non-existing name. Try to change age
command_result = customer_collection.update_one(
    {"name": "Non Existing Name"}, {"$set": {"age": 100}}
)

print(
    "Command: db.customer.updateOne(......find by non existing name, ......update age) | Result: ",
    command_result.raw_result,
)

# Filter by non-existing name. Update age. Provide upsert=True. New document created
command_result = customer_collection.update_one(
    {"name": "Non Existing Name"}, {"$set": {"age": 100}}, upsert=True
)

print(
    "Command: db.customer.updateOne(......find by non existing name, ......update age, .....provide upsert option) | Result: ",
    command_result.raw_result,
)

# Check upserted document
command_result = customer_collection.find_one({"name": "Non Existing Name"})
print(
    'Command: db.customer.find({ "name":  "Non Existing Name" }) | Result: ',
    command_result,
)


# Close connection
mongo_client.close()

Output:

Command: db.customer.insert_many(... 3 documents ) | Result:  [ObjectId('65d5d76e05b68aa456578491'), ObjectId('65d5d76e05b68aa456578492'), ObjectId('65d5d76e05b68aa456578493')]
Command: db.customer.find(obj_id) | Result:  {'_id': ObjectId('65d5d76e05b68aa456578491'), 'name': 'Izabella Conroy', 'age': 19, 'phone': '108-679-2154', 'address': {'street': '11 North Vineyard Drive', 'city': 'Pueblo West', 'state': 'CO', 'postalCode': '81007'}}
Command: db.customer.updateOne(......find by id, ......update name, age, city) | Result:  {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}
Command: db.customer.updateOne(......find by id, ......update state, age) | Result:  {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}
Command: db.customer.updateOne(......find by name, ......update age) | Result:  {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}
Command: db.customer.updateOne(......find by non existing name, ......update age) | Result:  {'n': 0, 'nModified': 0, 'ok': 1.0, 'updatedExisting': False}
Command: db.customer.updateOne(......find by non existing name, ......update age, .....provide upsert option) | Result:  {'n': 1, 'upserted': ObjectId('65d5d76ecd703a462ed37586'), 'nModified': 0, 'ok': 1.0, 'updatedExisting': False}
Command: db.customer.find({ "name":  "Non Existing Name" }) | Result:  {'_id': ObjectId('65d5d76ecd703a462ed37586'), 'name': 'Non Existing Name', 'age': 100}

NOTES

  • Use method “update_one” from redis-py.
  • Signature of the method is –
    • def update_one(
              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.updateOne() method example in Java

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

import java.util.Arrays;

public class UpdateOne {
    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
            Document doc1 = new Document("name", "Izabella Conroy")
                    .append("age", 19)
                    .append("phone", "108-679-2154")
                    .append("address", new Document("street", "11 North Vineyard Drive")
                            .append("city", "Pueblo West")
                            .append("state", "CO")
                            .append("postalCode", "81007"));
            Document doc2 = new Document("name", "Alisa Parker")
                    .append("age", 72)
                    .append("phone", "768-319-1054")
                    .append("address", new Document("street", "8532 Ingalls Circle")
                            .append("city", "Arvada")
                            .append("state", "CO")
                            .append("postalCode", "80003"));
            Document doc3 = new Document("name", "Eloise Weber")
                    .append("age", 29)
                    .append("phone", "618-357-2104")
                    .append("address", new Document("street", "632 Belmar Drive")
                            .append("city", "Edmond")
                            .append("state", "OK")
                            .append("postalCode", "73025"));
            customerCollection.insertMany(Arrays.asList(doc1, doc2, doc3));

            // Check the changed document
            ObjectId objId = (ObjectId) doc1.get("_id");
            Document result = customerCollection.find(new Document("_id", objId)).first();
            System.out.println("Command: db.customer.find(objId) | Result: " + result);

            // Select by id and change name, age, and city
            UpdateResult updateResult = customerCollection.updateOne(
                    new Document("_id", objId),
                    new Document("$set", new Document("name", "My Name Changed 9").append("age", 100).append("address.city", "city88"))
            );
            System.out.println("Command: db.customer.updateOne(......find by id, ......update name, age, city) | Result: " + updateResult);

            // Select by id. Change state. Increase age by 7
            updateResult = customerCollection.updateOne(
                    new Document("_id", objId),
                    new Document("$set", new Document("address.state", "ABC")).append("$inc", new Document("age", 7))
            );
            System.out.println("Command: db.customer.updateOne(......find by id, ......update state, age) | Result: " + updateResult);

            // Filter by name. Change age
            updateResult = customerCollection.updateOne(
                    new Document("name", "Alisa Parker"),
                    new Document("$set", new Document("age", 10))
            );
            System.out.println("Command: db.customer.updateOne(......find by name, ......update age) | Result: " + updateResult);

            // Filter by non-existing name. Try to change age
            updateResult = customerCollection.updateOne(
                    new Document("name", "Non Existing Name"),
                    new Document("$set", new Document("age", 100))
            );
            System.out.println("Command: db.customer.updateOne(......find by non existing name, ......update age) | Result: " + updateResult);

            // Filter by non-existing name. Update age. Provide upsert=true. New document created
            updateResult = customerCollection.updateOne(
                    new Document("name", "Non Existing Name"),
                    new Document("$set", new Document("age", 100)),
                    new com.mongodb.client.model.UpdateOptions().upsert(true)
            );
            System.out.println("Command: db.customer.updateOne(......find by non existing name, ......update age, .....provide upsert option) | Result: " + updateResult);

            // Check upserted document
            result = customerCollection.find(new Document("name", "Non Existing Name")).first();
            System.out.println("Command: db.customer.find({ \"name\":  \"Non Existing Name\" }) | Result: " + result);

            // Close the connection
            mongoClient.close();
        }
    }
}

Output:

Command: db.customer.find(objId) | Result: Document{{_id=65d5d9e3f961fd19e9b5b0af, name=Izabella Conroy, age=19, phone=108-679-2154, address=Document{{street=11 North Vineyard Drive, city=Pueblo West, state=CO, postalCode=81007}}}}
Command: db.customer.updateOne(......find by id, ......update name, age, city) | Result: AcknowledgedUpdateResult{matchedCount=1, modifiedCount=1, upsertedId=null}
Command: db.customer.updateOne(......find by id, ......update state, age) | Result: AcknowledgedUpdateResult{matchedCount=1, modifiedCount=1, upsertedId=null}
Command: db.customer.updateOne(......find by name, ......update age) | Result: AcknowledgedUpdateResult{matchedCount=1, modifiedCount=1, upsertedId=null}
Command: db.customer.updateOne(......find by non existing name, ......update age) | Result: AcknowledgedUpdateResult{matchedCount=0, modifiedCount=0, upsertedId=null}
Command: db.customer.updateOne(......find by non existing name, ......update age, .....provide upsert option) | Result: AcknowledgedUpdateResult{matchedCount=0, modifiedCount=0, upsertedId=BsonObjectId{value=65d5d9e3cd703a462ed3762b}}
Command: db.customer.find({ "name":  "Non Existing Name" }) | Result: Document{{_id=65d5d9e3cd703a462ed3762b, name=Non Existing Name, age=100}}

NOTES

  • Use the method “updateOne()” from MongoCollection.
  • Signatures of the method are-
    • UpdateResult updateOne(Bson filter, Bson update)
    • UpdateResult updateOne(Bson filter, Bson update, UpdateOptions updateOptions)
    • UpdateResult updateOne(ClientSession clientSession, Bson filter, Bson update)
    • UpdateResult updateOne(ClientSession clientSession, Bson filter, Bson update, UpdateOptions updateOptions)
    • UpdateResult updateOne(Bson filter, List<? extends Bson> update)
    • UpdateResult updateOne(Bson filter, List<? extends Bson> update, UpdateOptions updateOptions)
    • UpdateResult updateOne(ClientSession clientSession, Bson filter, List<? extends Bson> update)
    • UpdateResult updateOne(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.insertMany() Method Details
db.collection.findOne() Method Details

Leave a Comment


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