Introduction

Welcome to the fifth lesson in our course. In this lesson, we will focus on how to update and delete items in a NoSQL database. Being able to modify and remove data is essential for maintaining accurate and up-to-information in your applications. You will learn how to update specific fields in existing records, delete individual records, and efficiently remove multiple records at once. These skills are fundamental for managing data in any NoSQL environment.

Updating Fields in Firestore Documents

To update data in Firestore, you can modify specific fields within a document without replacing the entire document. This is done by referencing the document you want to update and specifying the fields and new values.

Here is an example of updating the content field of a document in the UserPosts collection, where the document ID is john_post1:

from google.cloud import firestore

db = firestore.Client()

# Reference to the document
doc_ref = db.collection('UserPosts').document('john_post1')

# Update the 'content' field
doc_ref.update({
    'content': 'Updated World!'
})

This operation changes only the specified field, leaving the other fields in the document unchanged. You must provide the correct document reference to ensure the update is applied to the intended item.

Deleting Documents in Firestore

To remove a document from a collection in Firestore, you use the delete() method on the document reference. This will permanently remove the document and all its fields from the database.

Here is how you would delete a document with the ID john_post2 from the UserPosts collection:

from google.cloud import firestore

db = firestore.Client()

# Reference to the document
doc_ref = db.collection('UserPosts').document('john_post2')

# Delete the document
doc_ref.delete()

Once deleted, the document and its data cannot be recovered. Make sure to double-check the document reference before performing a delete operation.

Deleting Multiple Documents At Once

Firestore allows you to perform batch operations, which can include deleting multiple documents in a single request. This is useful for efficiently removing several documents at once.

Here is an example of deleting two documents from the UserPosts collection using a batch operation:

from google.cloud import firestore

db = firestore.Client()
batch = db.batch()

# References to the documents to delete
doc_ref1 = db.collection('UserPosts').document('john_post1')
doc_ref2 = db.collection('UserPosts').document('anna_post1')

# Add delete operations to the batch
batch.delete(doc_ref1)
batch.delete(doc_ref2)

# Commit the batch operation
batch.commit()

Batch operations help reduce the number of separate requests and can make your data management tasks more efficient.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal