Cloud Firestore

Cloud Firestore is a NoSQL document database built for automatic scaling, highperformance, and ease of application development. While the Cloud Firestoreinterface has many of the same features as traditional databases, as a NoSQLdatabase it differs from them in the way it describes relationships between dataobjects.

For more information about Cloud Firestore, read theCloud FirestoreDocumentation.

The goal of google-cloud is to provide an API that is comfortable to Rubyists.Authentication is handled byFirestore.new. Youcan provide the project and credential information to connect to the CloudFirestore service, or if you are running on Google Cloud Platform (GCP),including Google Compute Engine (GCE), Google Kubernetes Engine (GKE), GoogleApp Engine (GAE), Google Cloud Functions (GCF) and Cloud Run this configurationis taken care of for you. You can read more about the options for connecting intheAuthentication Guide.

Adding data

Cloud Firestore stores data in Documents, which are stored in Collections. CloudFirestore creates collections and documents implicitly the first time you adddata to the document. (For more information, seeAdding Data to CloudFirestore.

To create or overwrite a single document, useClient#doc to obtain a documentreference. (This does not create a document in Cloud Firestore.) Then, callDocumentReference#set tocreate the document or overwrite an existing document:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a document referencenyc_ref=firestore.doc"cities/NYC"nyc_ref.set({name:"New York City"})# Document created

When you use this combination ofdoc andset to create a new document, youmust specify an ID for the document. (In the example above, the ID is "NYC".)However, if you do not have a meaningful ID for the document, you may omit theID from a call toCollectionReference#doc, and Cloud Firestore will auto-generate an ID for you.

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a collection referencecities_col=firestore.col"cities"# Get a document reference with datarandom_ref=cities_col.docrandom_ref.set({name:"New York City"})# The document ID is randomly generatedrandom_ref.document_id#=> "RANDOMID123XYZ"

You can perform both of the operations shown above, auto-generating an ID andcreating the document, in a single call toCollectionReference#add.

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a collection referencecities_col=firestore.col"cities"# Get a document reference with datarandom_ref=cities_col.add({name:"New York City"})# The document ID is randomly generatedrandom_ref.document_id#=> "RANDOMID123XYZ"

You can also useadd to create an empty document:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a collection referencecities_col=firestore.col"cities"# Create a document without datarandom_ref=cities_col.add# The document ID is randomly generatedrandom_ref.document_id#=> "RANDOMID123XYZ"

Retrieving collection references

Collections are simply named containers for documents. A collection containsdocuments and nothing else. It can't directly contain raw fields with values,and it can't contain other collections. You do not need to "create" or "delete"collections. After you create the first document in a collection, the collectionexists. If you delete all of the documents in a collection, it no longer exists.(For more information, seeCloud Firestore DataModel.)

UseClient#cols to list the root-levelcollections:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get the root collectionsfirestore.cols.eachdo|col|putscol.collection_idend

Retrieving a reference to a single root-level collection is similar:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get the cities collectioncities_col=firestore.col"cities"

To list the collections in a document, first get the document reference, thenuseDocumentReference#cols:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a document referencenyc_ref=firestore.doc"cities/NYC"nyc_ref.cols.eachdo|col|putscol.collection_idend

Again, retrieving a reference to a single collection is similar::

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a document referencenyc_ref=firestore.doc"cities/NYC"# Get precincts sub-collectionprecincts_col=nyc_ref.col"precincts"

Reading data

You can retrieve a snapshot of the data in a single document withDocumentReference#get, whichreturns an instance ofDocumentSnapshot:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a document referencenyc_ref=firestore.doc"cities/NYC"nyc_snap=nyc_ref.getnyc_snap[:population]#=> 1000000

In the example above,DocumentSnapshot#[] is used to access a top-level field. To access nestedfields, useFieldPath:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.newuser_snap=firestore.doc("users/frank").getnested_field_path=firestore.field_path:favorites,:fooduser_snap.get(nested_field_path)#=> "Pizza"

Or, useClient#get_all to retrieve alist of document snapshots (data):

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get and print city documentscities=["cities/NYC","cities/SF","cities/LA"]firestore.get_all(cities).eachdo|city|puts"#{city.document_id} has#{city[:population]} residents."end

To retrieve all of the document snapshots in a collection, useCollectionReference#get:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a collection referencecities_col=firestore.col"cities"# Get and print all city documentscities_col.getdo|city|puts"#{city.document_id} has#{city[:population]} residents."end

The example above is actually a simple query without filters. Let's look at someother queries for Cloud Firestore.

Querying data

UseQuery#where to filter queries on afield:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a collection referencecities_col=firestore.col"cities"# Create a queryquery=cities_col.where(:population,:>=,1000000)query.getdo|city|puts"#{city.document_id} has#{city[:population]} residents."end

You can order the query results withQuery#order:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a collection referencecities_col=firestore.col"cities"# Create a queryquery=cities_col.order(:name,:desc)query.getdo|city|puts"#{city.document_id} has#{city[:population]} residents."end

Query methods may be chained, as in this example usingQuery#limit andQuery#offset to perform pagination:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a collection referencecities_col=firestore.col"cities"# Create a queryquery=cities_col.limit(5).offset(10)query.getdo|city|puts"#{city.document_id} has#{city[:population]} residents."end

SeeManaging Indexes in CloudFirestore toensure the best performance for your queries.

Updating data

You can useDocumentReference#set to completely overwrite an existing document:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a document referencenyc_ref=firestore.doc"cities/NYC"nyc_ref.set({name:"New York City"})

Or, to selectively update only the fields appearing in yourdata argument, setthemerge option totrue:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a document referencenyc_ref=firestore.doc"cities/NYC"nyc_ref.set({name:"New York City"},merge:true)

UseDocumentReference#update to directly update a deeply-nested field with aGoogle::Cloud::Firestore::FieldPath:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.newuser_ref=firestore.doc"users/frank"nested_field_path=firestore.field_path:favorites,:fooduser_ref.update({nested_field_path=>"Pasta"})

Listening for changes

You can listen to a document reference or a collection reference/query forchanges. The current document snapshot or query results snapshot will be yieldedfirst, and each time the contents change.

You can useDocumentReference#listen to be notified of changes to a single document:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a document referencenyc_ref=firestore.doc"cities/NYC"listener=nyc_ref.listendo|snapshot|puts"The population of#{snapshot[:name]} "puts"is#{snapshot[:population]}."end# When ready, stop the listen operation and close the stream.listener.stop

You can useQuery#listen to be notifiedof changes to any document contained in the query:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Create a queryquery=firestore.col(:cities).order(:population,:desc)listener=query.listendo|snapshot|puts"The query snapshot has#{snapshot.docs.count} documents "puts"and has#{snapshot.changes.count} changes."end# When ready, stop the listen operation and close the stream.listener.stop

Using transactions and batched writes

Cloud Firestore supports atomic operations for reading and writing data. In aset of atomic operations, either all of the operations succeed, or none of themare applied. There are two types of atomic operations in Cloud Firestore: Atransaction is a set of read and write operations on one or more documents,while a batched write is a set of only write operations on one or moredocuments. (For more information, seeTransactions and BatchedWrites.

Transactions

A transaction consists of any number of read operations followed by any numberof write operations. (Read operations must always come before write operations.)In the case of a concurrent update by another client, Cloud Firestore runs theentire transaction again. Therefore, transaction blocks should be idempotent andshould not not directly modify application state.

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.newcity=firestore.col("cities").doc("SF")city.set({name:"San Francisco",state:"CA",country:"USA",capital:false,population:860000})firestore.transactiondo|tx|new_population=tx.get(city).data[:population]+1tx.update(city,{population:new_population})end

Batched writes

If you do not need to read any documents in your operation set, you can executemultiple write operations as a single batch. A batch of writes completesatomically and can write to multiple documents. Batched writes are also usefulfor migrating large data sets to Cloud Firestore.

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.newfirestore.batchdo|b|# Set the data for NYCb.set("cities/NYC",{name:"New York City"})# Update the population for SFb.update("cities/SF",{population:1000000})# Delete LAb.delete("cities/LA")end

Deleting data

UseDocumentReference#delete to delete a document from Cloud Firestore:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a document referencenyc_ref=firestore.doc"cities/NYC"nyc_ref.delete

To delete specific fields from a document, use theClient.field_delete method whenyou update a document:

require"google/cloud/firestore"firestore=Google::Cloud::Firestore.new# Get a document referencenyc_ref=firestore.doc"cities/NYC"nyc_ref.update({name:"New York City",trash:firestore.field_delete})

To delete an entire collection or sub-collection in Cloud Firestore, retrieveall the documents within the collection or sub-collection and delete them. Ifyou have larger collections, you may want to delete the documents in smallerbatches to avoid out-of-memory errors. Repeat the process until you've deletedthe entire collection or sub-collection.

Additional information

Google Firestore can be configured to use gRPC's logging. To learn more, see theLogging guide.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-11-01 UTC.