If you use the web or mobile client libraries, authenticate with security rules. For more information, seeGetting started with security rules.
If you use the server client libraries or REST API, authenticate with Identity and Access Management (IAM). For more information, seeSecurity for server client libraries.
TheCloud FirestoreSDK is initialized in different ways depending on
your environment. Below are the most common methods. For a complete reference,
seeInitialize
the Admin SDK.
Initialize onGoogle Cloud
importcom.google.auth.oauth2.GoogleCredentials;importcom.google.cloud.firestore.Firestore;importcom.google.firebase.FirebaseApp;importcom.google.firebase.FirebaseOptions;// Use the application default credentialsGoogleCredentialscredentials=GoogleCredentials.getApplicationDefault();FirebaseOptionsoptions=newFirebaseOptions.Builder().setCredentials(credentials).setProjectId(projectId).build();FirebaseApp.initializeApp(options);Firestoredb=FirestoreClient.getFirestore();
Initialize on your own server
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accountsin the Google Cloud console. Generate a new private key and save the JSON
file. Then use the file to initialize the SDK:
importcom.google.auth.oauth2.GoogleCredentials;importcom.google.cloud.firestore.Firestore;importcom.google.firebase.FirebaseApp;importcom.google.firebase.FirebaseOptions;// Use a service accountInputStreamserviceAccount=newFileInputStream("path/to/serviceAccount.json");GoogleCredentialscredentials=GoogleCredentials.fromStream(serviceAccount);FirebaseOptionsoptions=newFirebaseOptions.Builder().setCredentials(credentials).build();FirebaseApp.initializeApp(options);Firestoredb=FirestoreClient.getFirestore();
Python
TheCloud FirestoreSDK is initialized in different ways depending on
your environment. Below are the most common methods. For a complete reference,
seeInitialize
the Admin SDK.
Initialize onGoogle Cloud
importfirebase_adminfromfirebase_adminimportfirestore# Application Default credentials are automatically created.app=firebase_admin.initialize_app()db=firestore.client()
An existing application default credential can also be used to initialize the SDK.
importfirebase_adminfromfirebase_adminimportcredentialsfromfirebase_adminimportfirestore# Use the application default credentials.cred=credentials.ApplicationDefault()firebase_admin.initialize_app(cred)db=firestore.client()
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accountsin the Google Cloud console. Generate a new private key and save the JSON
file. Then use the file to initialize the SDK:
importfirebase_adminfromfirebase_adminimportcredentialsfromfirebase_adminimportfirestore# Use a service account.cred=credentials.Certificate('path/to/serviceAccount.json')app=firebase_admin.initialize_app(cred)db=firestore.client()
TheCloud FirestoreSDK is initialized in different ways depending on
your environment. Below are the most common methods. For a complete reference,
seeInitialize
the Admin SDK.
Initialize onGoogle Cloud
importfirebase_adminfromfirebase_adminimportfirestore_async# Application Default credentials are automatically created.app=firebase_admin.initialize_app()db=firestore_async.client()
An existing application default credential can also be used to initialize the SDK.
importfirebase_adminfromfirebase_adminimportcredentialsfromfirebase_adminimportfirestore_async# Use the application default credentials.cred=credentials.ApplicationDefault()firebase_admin.initialize_app(cred)db=firestore_async.client()
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accountsin the Google Cloud console. Generate a new private key and save the JSON
file. Then use the file to initialize the SDK:
importfirebase_adminfromfirebase_adminimportcredentialsfromfirebase_adminimportfirestore_async# Use a service account.cred=credentials.Certificate('path/to/serviceAccount.json')app=firebase_admin.initialize_app(cred)db=firestore_async.client()
TheCloud FirestoreSDK is initialized in different ways depending on
your environment. Below are the most common methods. For a complete reference,
seeInitialize
the Admin SDK.
To use the Firebase Admin SDK on your own server (or any other Node.js environment),
use aservice account.
Go toIAM & admin > Service accountsin the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
TheCloud FirestoreSDK is initialized in different ways depending on
your environment. Below are the most common methods. For a complete reference,
seeInitialize
the Admin SDK.
Initialize onGoogle Cloud
import("log"firebase"firebase.google.com/go""google.golang.org/api/option")// Use the application default credentialsctx:=context.Background()conf:=&firebase.Config{ProjectID:projectID}app,err:=firebase.NewApp(ctx,conf)iferr!=nil{log.Fatalln(err)}client,err:=app.Firestore(ctx)iferr!=nil{log.Fatalln(err)}deferclient.Close()
Initialize on your own server
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accountsin the Google Cloud console. Generate a new private key and save the JSON
file. Then use the file to initialize the SDK:
import("log"firebase"firebase.google.com/go""google.golang.org/api/option")// Use a service accountctx:=context.Background()sa:=option.WithCredentialsFile("path/to/serviceAccount.json")app,err:=firebase.NewApp(ctx,nil,sa)iferr!=nil{log.Fatalln(err)}client,err:=app.Firestore(ctx)iferr!=nil{log.Fatalln(err)}deferclient.Close()
use Google\Cloud\Firestore\FirestoreClient;/*** Initialize Cloud Firestore with default project ID.*/function setup_client_create(string $projectId = null){// Create the Cloud Firestore clientif (empty($projectId)) {// The `projectId` parameter is optional and represents which project the// client will act on behalf of. If not supplied, the client falls back to// the default project inferred from the environment.$db = new FirestoreClient();printf('Created Cloud Firestore client with default project ID.' . PHP_EOL);} else {$db = new FirestoreClient(['projectId' => $projectId,]);printf('Created Cloud Firestore client with project ID: %s' . PHP_EOL, $projectId);}}
require"google/cloud/firestore"# The `project_id` parameter is optional and represents which project the# client will act on behalf of. If not supplied, the client falls back to the# default project inferred from the environment.firestore=Google::Cloud::Firestore.newproject_id:project_idputs"Created Cloud Firestore client with given project ID."
To create or overwrite a single document, use the following language-specificset()methods:
Web
Use thesetDoc()method:
import{doc,setDoc}from"firebase/firestore";// Add a new document in collection "cities"awaitsetDoc(doc(db,"cities","LA"),{name:"Los Angeles",state:"CA",country:"USA"});
// Add a new document in collection "cities"db.collection("cities").doc("LA").set({name:"Los Angeles",state:"CA",country:"USA"}).then(()=>{console.log("Document successfully written!");}).catch((error)=>{console.error("Error writing document: ",error);});
Note:This product is not available on watchOS and App Clip targets.
// Add a new document in collection "cities"do{tryawaitdb.collection("cities").document("LA").setData(["name":"Los Angeles","state":"CA","country":"USA"])print("Document successfully written!")}catch{print("Error writing document:\(error)")}
Note:This product is not available on watchOS and App Clip targets.
// Add a new document in collection "cities"[[[self.dbcollectionWithPath:@"cities"]documentWithPath:@"LA"]setData:@{@"name":@"Los Angeles",@"state":@"CA",@"country":@"USA"}completion:^(NSError*_Nullableerror){if(error!=nil){NSLog(@"Error writing document: %@",error);}else{NSLog(@"Document successfully written!");}}];
// Create a Map to store the data we want to setMap<String,Object>docData=newHashMap<>();docData.put("name","Los Angeles");docData.put("state","CA");docData.put("country","USA");docData.put("regions",Arrays.asList("west_coast","socal"));// Add a new document (asynchronously) in collection "cities" with id "LA"ApiFuture<WriteResult>future=db.collection("cities").document("LA").set(docData);// ...// future.get() blocks on responseSystem.out.println("Update time : "+future.get().getUpdateTime());
data={"name":"Los Angeles","state":"CA","country":"USA"}# Add a new doc in collection 'cities' with ID 'LA'db.collection("cities").document("LA").set(data)
data={"name":"Los Angeles","state":"CA","country":"USA"}# Add a new doc in collection 'cities' with ID 'LA'awaitdb.collection("cities").document("LA").set(data)
constdata={name:'Los Angeles',state:'CA',country:'USA'};// Add a new document in collection "cities" with ID 'LA'constres=awaitdb.collection('cities').doc('LA').set(data);
import("context""log""cloud.google.com/go/firestore")funcaddDocAsMap(ctxcontext.Context,client*firestore.Client)error{_,err:=client.Collection("cities").Doc("LA").Set(ctx,map[string]interface{}{"name":"Los Angeles","state":"CA","country":"USA",})iferr!=nil{// Handle any errors in an appropriate way, such as returning them.log.Printf("An error has occurred: %s",err)}returnerr}
DocumentReferencedocRef=db.Collection("cities").Document("LA");Dictionary<string,object>city=newDictionary<string,object>{{"Name","Los Angeles"},{"State","CA"},{"Country","USA"}};docRef.SetAsync(city).ContinueWithOnMainThread(task=>{Debug.Log("Added data to the LA document in the cities collection.");});
If the document does not exist, it will be created. If the document does exist,
its contents will be overwritten with the newly provided data, unless you
specify that the data should be merged into the existing document, as follows:
Note:This product is not available on watchOS and App Clip targets.
// Write to the document reference, merging data with existing// if the document already exists[[[self.dbcollectionWithPath:@"cities"]documentWithPath:@"BJ"]setData:@{@"capital":@YES}merge:YEScompletion:^(NSError*_Nullableerror){// ...}];
// Update one field, creating the document if it does not already exist.valdata=hashMapOf("capital"totrue)db.collection("cities").document("BJ").set(data,SetOptions.merge())
// Update one field, creating the document if it does not already exist.Map<String,Object>data=newHashMap<>();data.put("capital",true);db.collection("cities").document("BJ").set(data,SetOptions.merge());
// Update one field, creating the document if it does not already exist.finaldata={"capital":true};db.collection("cities").doc("BJ").set(data,SetOptions(merge:true));
// asynchronously update doc, create the document if missingMap<String,Object>update=newHashMap<>();update.put("capital",true);ApiFuture<WriteResult>writeResult=db.collection("cities").document("BJ").set(update,SetOptions.merge());// ...System.out.println("Update time : "+writeResult.get().getUpdateTime());
import("context""log""cloud.google.com/go/firestore")funcupdateDocCreateIfMissing(ctxcontext.Context,client*firestore.Client)error{_,err:=client.Collection("cities").Doc("BJ").Set(ctx,map[string]interface{}{"capital":true,},firestore.MergeAll)iferr!=nil{// Handle any errors in an appropriate way, such as returning them.log.Printf("An error has occurred: %s",err)}returnerr}
If you're not sure whether the document exists, pass the option to merge the new
data with any existing document to avoid overwriting entire documents. For
documents that contain maps, if you specify a set with a field that contains an
empty map, the map field of the target document is overwritten.
Data types
Cloud Firestorelets you write a variety of data types inside a document,
including strings, booleans, numbers, dates, null, and nested arrays and
objects.Cloud Firestorealways stores numbers as doubles, regardless of
what type of number you use in your code.
Map<String,Object>docData=newHashMap<>();docData.put("stringExample","Hello, World");docData.put("booleanExample",false);docData.put("numberExample",3.14159265);docData.put("nullExample",null);ArrayList<Object>arrayExample=newArrayList<>();Collections.addAll(arrayExample,5L,true,"hello");docData.put("arrayExample",arrayExample);Map<String,Object>objectExample=newHashMap<>();objectExample.put("a",5L);objectExample.put("b",true);docData.put("objectExample",objectExample);ApiFuture<WriteResult>future=db.collection("data").document("one").set(docData);System.out.println("Update time : "+future.get().getUpdateTime());
import("context""log""time""cloud.google.com/go/firestore")funcaddDocDataTypes(ctxcontext.Context,client*firestore.Client)error{doc:=make(map[string]interface{})doc["stringExample"]="Hello world!"doc["booleanExample"]=truedoc["numberExample"]=3.14159265doc["dateExample"]=time.Now()doc["arrayExample"]=[]interface{}{5,true,"hello"}doc["nullExample"]=nildoc["objectExample"]=map[string]interface{}{"a":5,"b":true,}_,err:=client.Collection("data").Doc("one").Set(ctx,doc)iferr!=nil{// Handle any errors in an appropriate way, such as returning them.log.Printf("An error has occurred: %s",err)}returnerr}
UsingMaporDictionaryobjects to represent your documents is often
inconvenient, soCloud Firestoresupports writing documents with custom
classes.Cloud Firestoreconverts the objects to supported data types.
Using custom classes, you can rewrite the initial example in the following way:
Web
classCity{constructor(name,state,country){this.name=name;this.state=state;this.country=country;}toString(){returnthis.name+', '+this.state+', '+this.country;}}// Firestore data converterconstcityConverter={toFirestore:(city)=>{return{name:city.name,state:city.state,country:city.country};},fromFirestore:(snapshot,options)=>{constdata=snapshot.data(options);returnnewCity(data.name,data.state,data.country);}};
Note:This product is not available on watchOS and App Clip targets.
// This isn't supported in Objective-C.
Kotlin
dataclassCity(valname:String?=null,valstate:String?=null,valcountry:String?=null,@field:JvmField// use this annotation if your Boolean field is prefixed with 'is'valisCapital:Boolean?=null,valpopulation:Long?=null,valregions:List<String>?=null,)
publicCity(){// Must have a public no-argument constructor}// Initialize all fields of a citypublicCity(Stringname,Stringstate,Stringcountry,Booleancapital,Longpopulation,List<String>regions){this.name=name;this.state=state;this.country=country;this.capital=capital;this.population=population;this.regions=regions;}
// City represents a city.typeCitystruct{Namestring`firestore:"name,omitempty"`Statestring`firestore:"state,omitempty"`Countrystring`firestore:"country,omitempty"`Capitalbool`firestore:"capital,omitempty"`Populationint64`firestore:"population,omitempty"`Densityint64`firestore:"density,omitempty"`Regions[]string`firestore:"regions,omitempty"`}
import{doc,setDoc}from"firebase/firestore";// Set with cityConverterconstref=doc(db,"cities","LA").withConverter(cityConverter);awaitsetDoc(ref,newCity("Los Angeles","CA","USA"));
Note:This product is not available on watchOS and App Clip targets.
letcity=City(name:"Los Angeles",state:"CA",country:"USA",isCapital:false,population:5000000)do{trydb.collection("cities").document("LA").setData(from:city)}catchleterror{print("Error writing city to Firestore:\(error)")}
Citycity=newCity("Los Angeles","CA","USA",false,3900000L,Arrays.asList("west_coast","socal"));ApiFuture<WriteResult>future=db.collection("cities").document("LA").set(city);// block on response if requiredSystem.out.println("Update time : "+future.get().getUpdateTime());
import("context""log""cloud.google.com/go/firestore")funcaddDocAsEntity(ctxcontext.Context,client*firestore.Client)error{city:=City{Name:"Los Angeles",Country:"USA",}_,err:=client.Collection("cities").Doc("LA").Set(ctx,city)iferr!=nil{// Handle any errors in an appropriate way, such as returning them.log.Printf("An error has occurred: %s",err)}returnerr}
import("context""log""cloud.google.com/go/firestore")funcaddDocWithID(ctxcontext.Context,client*firestore.Client)error{vardata=make(map[string]interface{})_,err:=client.Collection("cities").Doc("new-city-id").Set(ctx,data)iferr!=nil{// Handle any errors in an appropriate way, such as returning them.log.Printf("An error has occurred: %s",err)}returnerr}
If there isn't a meaningful ID for the document,Cloud Firestorecan
auto-generate an ID for you. You can call the following language-specificadd()methods:
Web
Use theaddDoc()method:
import{collection,addDoc}from"firebase/firestore";// Add a new document with a generated id.constdocRef=awaitaddDoc(collection(db,"cities"),{name:"Tokyo",country:"Japan"});console.log("Document written with ID: ",docRef.id);
// Add a new document with a generated id.db.collection("cities").add({name:"Tokyo",country:"Japan"}).then((docRef)=>{console.log("Document written with ID: ",docRef.id);}).catch((error)=>{console.error("Error adding document: ",error);});
Note:This product is not available on watchOS and App Clip targets.
// Add a new document with a generated id.do{letref=tryawaitdb.collection("cities").addDocument(data:["name":"Tokyo","country":"Japan"])print("Document added with ID:\(ref.documentID)")}catch{print("Error adding document:\(error)")}
Note:This product is not available on watchOS and App Clip targets.
// Add a new document with a generated id.__blockFIRDocumentReference*ref=[[self.dbcollectionWithPath:@"cities"]addDocumentWithData:@{@"name":@"Tokyo",@"country":@"Japan"}completion:^(NSError*_Nullableerror){if(error!=nil){NSLog(@"Error adding document: %@",error);}else{NSLog(@"Document added with ID: %@",ref.documentID);}}];
// Add a new document with a generated id.valdata=hashMapOf("name"to"Tokyo","country"to"Japan",)db.collection("cities").add(data).addOnSuccessListener{documentReference->Log.d(TAG,"DocumentSnapshot written with ID:${documentReference.id}")}.addOnFailureListener{e->Log.w(TAG,"Error adding document",e)}
// Add a new document with a generated id.Map<String,Object>data=newHashMap<>();data.put("name","Tokyo");data.put("country","Japan");db.collection("cities").add(data).addOnSuccessListener(newOnSuccessListener<DocumentReference>(){@OverridepublicvoidonSuccess(DocumentReferencedocumentReference){Log.d(TAG,"DocumentSnapshot written with ID: "+documentReference.getId());}}).addOnFailureListener(newOnFailureListener(){@OverridepublicvoidonFailure(@NonNullExceptione){Log.w(TAG,"Error adding document",e);}});
// Add a new document with a generated id.finaldata={"name":"Tokyo","country":"Japan"};db.collection("cities").add(data).then((documentSnapshot)=>print("Added Data with ID:${documentSnapshot.id}"));
// Add document data with auto-generated id.Map<String,Object>data=newHashMap<>();data.put("name","Tokyo");data.put("country","Japan");ApiFuture<DocumentReference>addedDocRef=db.collection("cities").add(data);System.out.println("Added document with ID: "+addedDocRef.get().getId());
// Add a new document with a generated id.constres=awaitdb.collection('cities').add({name:'Tokyo',country:'Japan'});console.log('Added document with ID: ',res.id);
import("context""log""cloud.google.com/go/firestore")funcaddDocWithoutID(ctxcontext.Context,client*firestore.Client)error{_,_,err:=client.Collection("cities").Add(ctx,map[string]interface{}{"name":"Tokyo","country":"Japan",})iferr!=nil{// Handle any errors in an appropriate way, such as returning them.log.Printf("An error has occurred: %s",err)}returnerr}
Dictionary<string,object>city=newDictionary<string,object>{{"Name","Tokyo"},{"Country","Japan"}};db.Collection("cities").AddAsync(city).ContinueWithOnMainThread(task=>{DocumentReferenceaddedDocRef=task.Result;Debug.Log(String.Format("Added document with ID: {0}.",addedDocRef.Id));});
C#
Use theAddAsync()method:
Dictionary<string,object>city=newDictionary<string,object>{{"Name","Tokyo"},{"Country","Japan"}};DocumentReferenceaddedDocRef=awaitdb.Collection("cities").AddAsync(city);Console.WriteLine("Added document with ID: {0}.",addedDocRef.Id);
data={name:"Tokyo",country:"Japan"}cities_ref=firestore.colcollection_pathadded_doc_ref=cities_ref.adddataputs"Added document with ID:#{added_doc_ref.document_id}."
In some cases, it can be useful to create a document reference with an
auto-generated ID, then use the reference later. For this use case, you can calldoc()in the following way:
Web
import{collection,doc,setDoc}from"firebase/firestore";// Add a new document with a generated idconstnewCityRef=doc(collection(db,"cities"));// later...awaitsetDoc(newCityRef,data);
// Add document data after generating an id.DocumentReferenceaddedDocRef=db.collection("cities").document();System.out.println("Added document with ID: "+addedDocRef.getId());// later...ApiFuture<WriteResult>writeResult=addedDocRef.set(data);
import("context""log""cloud.google.com/go/firestore")funcaddDocAfterAutoGeneratedID(ctxcontext.Context,client*firestore.Client)error{data:=City{Name:"Sydney",Country:"Australia",}ref:=client.Collection("cities").NewDoc()// later..._,err:=ref.Set(ctx,data)iferr!=nil{// Handle any errors in an appropriate way, such as returning them.log.Printf("An error has occurred: %s",err)}returnerr}
DocumentReferenceaddedDocRef=db.Collection("cities").Document();Debug.Log(String.Format("Added document with ID: {0}.",addedDocRef.Id));addedDocRef.SetAsync(city).ContinueWithOnMainThread(task=>{Debug.Log(String.Format("Added data to the {0} document in the cities collection.",addedDocRef.Id));});
C#
DocumentReferenceaddedDocRef=db.Collection("cities").Document();Console.WriteLine("Added document with ID: {0}.",addedDocRef.Id);awaitaddedDocRef.SetAsync(city);
In the backend,.add(...)and.doc().set(...)are equivalent, so you can use
either option.
Update a document
To update some fields of a document without overwriting the entire document, use
the following language-specificupdate()methods:
Web
Use theupdateDoc()method:
import{doc,updateDoc}from"firebase/firestore";constwashingtonRef=doc(db,"cities","DC");// Set the "capital" field of the city 'DC'awaitupdateDoc(washingtonRef,{capital:true});
varwashingtonRef=db.collection("cities").doc("DC");// Set the "capital" field of the city 'DC'returnwashingtonRef.update({capital:true}).then(()=>{console.log("Document successfully updated!");}).catch((error)=>{// The document probably doesn't exist.console.error("Error updating document: ",error);});
Note:This product is not available on watchOS and App Clip targets.
letwashingtonRef=db.collection("cities").document("DC")// Set the "capital" field of the city 'DC'do{tryawaitwashingtonRef.updateData(["capital":true])print("Document successfully updated")}catch{print("Error updating document:\(error)")}
Note:This product is not available on watchOS and App Clip targets.
FIRDocumentReference*washingtonRef=[[self.dbcollectionWithPath:@"cities"]documentWithPath:@"DC"];// Set the "capital" field of the city[washingtonRefupdateData:@{@"capital":@YES}completion:^(NSError*_Nullableerror){if(error!=nil){NSLog(@"Error updating document: %@",error);}else{NSLog(@"Document successfully updated");}}];
valwashingtonRef=db.collection("cities").document("DC")// Set the "isCapital" field of the city 'DC'washingtonRef.update("capital",true).addOnSuccessListener{Log.d(TAG,"DocumentSnapshot successfully updated!")}.addOnFailureListener{e->Log.w(TAG,"Error updating document",e)}
DocumentReferencewashingtonRef=db.collection("cities").document("DC");// Set the "isCapital" field of the city 'DC'washingtonRef.update("capital",true).addOnSuccessListener(newOnSuccessListener<Void>(){@OverridepublicvoidonSuccess(VoidaVoid){Log.d(TAG,"DocumentSnapshot successfully updated!");}}).addOnFailureListener(newOnFailureListener(){@OverridepublicvoidonFailure(@NonNullExceptione){Log.w(TAG,"Error updating document",e);}});
DocumentReferencewashington_ref=db->Collection("cities").Document("DC");// Set the "capital" field of the city "DC".washington_ref.Update({{"capital", FieldValue::Boolean(true)}});
import("context""log""cloud.google.com/go/firestore")funcupdateDoc(ctxcontext.Context,client*firestore.Client)error{// ..._,err:=client.Collection("cities").Doc("DC").Update(ctx,[]firestore.Update{{Path:"capital",Value:true,},})iferr!=nil{// Handle any errors in an appropriate way, such as returning them.log.Printf("An error has occurred: %s",err)}returnerr}
DocumentReferencecityRef=db.Collection("cities").Document("new-city-id");Dictionary<string,object>updates=newDictionary<string,object>{{"Capital",false}};cityRef.UpdateAsync(updates).ContinueWithOnMainThread(task=>{Debug.Log("Updated the Capital field of the new-city-id document in the cities collection.");});// You can also update a single field with: cityRef.UpdateAsync("Capital", false);
C#
Use theUpdateAsync()method:
DocumentReferencecityRef=db.Collection("cities").Document("new-city-id");Dictionary<string,object>updates=newDictionary<string,object>{{"Capital",false}};awaitcityRef.UpdateAsync(updates);// You can also update a single field with: await cityRef.UpdateAsync("Capital", false);
You can set a field in your document to a server timestamp which tracks when
the server receives the update.
Web
import{updateDoc,serverTimestamp}from"firebase/firestore";constdocRef=doc(db,'objects','some-id');// Update the timestamp field with the value from the serverconstupdateTimestamp=awaitupdateDoc(docRef,{timestamp:serverTimestamp()});
vardocRef=db.collection('objects').doc('some-id');// Update the timestamp field with the value from the servervarupdateTimestamp=docRef.update({timestamp:firebase.firestore.FieldValue.serverTimestamp()});
// If you're using custom Kotlin objects in Android, add an @ServerTimestamp// annotation to a Date field for your custom object classes. This indicates// that the Date field should be treated as a server timestamp by the object mapper.valdocRef=db.collection("objects").document("some-id")// Update the timestamp field with the value from the servervalupdates=hashMapOf<String,Any>("timestamp"toFieldValue.serverTimestamp(),)docRef.update(updates).addOnCompleteListener{}
// If you're using custom Java objects in Android, add an @ServerTimestamp// annotation to a Date field for your custom object classes. This indicates// that the Date field should be treated as a server timestamp by the object mapper.DocumentReferencedocRef=db.collection("objects").document("some-id");// Update the timestamp field with the value from the serverMap<String,Object>updates=newHashMap<>();updates.put("timestamp",FieldValue.serverTimestamp());docRef.update(updates).addOnCompleteListener(newOnCompleteListener<Void>(){// ...// ...
DocumentReferencedocRef=db.collection("objects").document("some-id");// Update the timestamp field with the value from the serverApiFuture<WriteResult>writeResult=docRef.update("timestamp",FieldValue.serverTimestamp());System.out.println("Update time : "+writeResult.get());
// Create a document referenceconstdocRef=db.collection('objects').doc('some-id');// Update the timestamp field with the value from the serverconstres=awaitdocRef.update({timestamp:FieldValue.serverTimestamp()});
import("context""log""cloud.google.com/go/firestore")funcupdateDocServerTimestamp(ctxcontext.Context,client*firestore.Client)error{// ..._,err:=client.Collection("objects").Doc("some-id").Set(ctx,map[string]interface{}{"timestamp":firestore.ServerTimestamp,},firestore.MergeAll)iferr!=nil{// Handle any errors in an appropriate way, such as returning them.log.Printf("An error has occurred: %s",err)}returnerr}
DocumentReferencecityRef=db.Collection("cities").Document("new-city-id");cityRef.UpdateAsync("Timestamp",FieldValue.ServerTimestamp).ContinueWithOnMainThread(task=>{Debug.Log("Updated the Timestamp field of the new-city-id document in the cities "+"collection.");});
When updating multiple timestamp fields inside of atransaction, each field receives the same server timestamp
value.
Update fields in nested objects
If your document contains nested objects, you can use thedot notationto
reference nested fields within the document when you callupdate():
Web
import{doc,setDoc,updateDoc}from"firebase/firestore";// Create an initial document to update.constfrankDocRef=doc(db,"users","frank");awaitsetDoc(frankDocRef,{name:"Frank",favorites:{food:"Pizza",color:"Blue",subject:"recess"},age:12});// To update age and favorite color:awaitupdateDoc(frankDocRef,{"age":13,"favorites.color":"Red"});
// Create an initial document to update.varfrankDocRef=db.collection("users").doc("frank");frankDocRef.set({name:"Frank",favorites:{food:"Pizza",color:"Blue",subject:"recess"},age:12});// To update age and favorite color:db.collection("users").doc("frank").update({"age":13,"favorites.color":"Red"}).then(()=>{console.log("Document successfully updated!");});
Note:This product is not available on watchOS and App Clip targets.
// Create an initial document to update.letfrankDocRef=db.collection("users").document("frank")do{tryawaitfrankDocRef.setData(["name":"Frank","favorites":["food":"Pizza","color":"Blue","subject":"recess"],"age":12])// To update age and favorite color:tryawaitfrankDocRef.updateData(["age":13,"favorites.color":"Red"])print("Document successfully updated")}catch{print("Error updating document:\(error)")}
Note:This product is not available on watchOS and App Clip targets.
// Create an initial document to update.FIRDocumentReference*frankDocRef=[[self.dbcollectionWithPath:@"users"]documentWithPath:@"frank"];[frankDocRefsetData:@{@"name":@"Frank",@"favorites":@{@"food":@"Pizza",@"color":@"Blue",@"subject":@"recess"},@"age":@12}];// To update age and favorite color:[frankDocRefupdateData:@{@"age":@13,@"favorites.color":@"Red",}completion:^(NSError*_Nullableerror){if(error!=nil){NSLog(@"Error updating document: %@",error);}else{NSLog(@"Document successfully updated");}}];
// Create an initial document to updateDocumentReferencefrankDocRef=db.collection("users").document("frank");Map<String,Object>initialData=newHashMap<>();initialData.put("name","Frank");initialData.put("age",12);Map<String,Object>favorites=newHashMap<>();favorites.put("food","Pizza");favorites.put("color","Blue");favorites.put("subject","Recess");initialData.put("favorites",favorites);ApiFuture<WriteResult>initialResult=frankDocRef.set(initialData);// Confirm that data has been successfully saved by blocking on the operationinitialResult.get();// Update age and favorite colorMap<String,Object>updates=newHashMap<>();updates.put("age",13);updates.put("favorites.color","Red");// Async update documentApiFuture<WriteResult>writeResult=frankDocRef.update(updates);// ...System.out.println("Update time : "+writeResult.get().getUpdateTime());
# Create an initial document to updatefrank_ref=db.collection("users").document("frank")frank_ref.set({"name":"Frank","favorites":{"food":"Pizza","color":"Blue","subject":"Recess"},"age":12,})# Update age and favorite colorfrank_ref.update({"age":13,"favorites.color":"Red"})
# Create an initial document to updatefrank_ref=db.collection("users").document("frank")awaitfrank_ref.set({"name":"Frank","favorites":{"food":"Pizza","color":"Blue","subject":"Recess"},"age":12,})# Update age and favorite colorawaitfrank_ref.update({"age":13,"favorites.color":"Red"})
import("context""log""cloud.google.com/go/firestore")funcupdateDocNested(ctxcontext.Context,client*firestore.Client)error{initialData:=map[string]interface{}{"name":"Frank","age":12,"favorites":map[string]interface{}{"food":"Pizza","color":"Blue","subject":"recess",},}// ..._,err:=client.Collection("users").Doc("frank").Set(ctx,map[string]interface{}{"age":13,"favorites":map[string]interface{}{"color":"Red",},},firestore.MergeAll)iferr!=nil{// Handle any errors in an appropriate way, such as returning them.log.Printf("An error has occurred: %s",err)}returnerr}
DocumentReferencefrankDocRef=db.Collection("users").Document("frank");Dictionary<string,object>initialData=newDictionary<string,object>{{"Name","Frank"},{"Age",12}};Dictionary<string,object>favorites=newDictionary<string,object>{{"Food","Pizza"},{"Color","Blue"},{"Subject","Recess"},};initialData.Add("Favorites",favorites);frankDocRef.SetAsync(initialData).ContinueWithOnMainThread(task=>{// Update age and favorite colorDictionary<string,object>updates=newDictionary<string,object>{{"Age",13},{"Favorites.Color","Red"},};// Asynchronously update the documentreturnfrankDocRef.UpdateAsync(updates);}).ContinueWithOnMainThread(task=>{Debug.Log("Updated the age and favorite color fields of the Frank document in "+"the users collection.");});
C#
DocumentReferencefrankDocRef=db.Collection("users").Document("frank");Dictionary<string,object>initialData=newDictionary<string,object>{{"Name","Frank"},{"Age",12}};Dictionary<string,object>favorites=newDictionary<string,object>{{"Food","Pizza"},{"Color","Blue"},{"Subject","Recess"},};initialData.Add("Favorites",favorites);awaitfrankDocRef.SetAsync(initialData);// Update age and favorite colorDictionary<string,object>updates=newDictionary<string,object>{{"Age",13},{"Favorites.Color","Red"},};// Asynchronously update the documentawaitfrankDocRef.UpdateAsync(updates);
# Create an initial document to updatefrank_ref=firestore.doc"#{collection_path}/frank"frank_ref.set({name:"Frank",favorites:{food:"Pizza",color:"Blue",subject:"Recess"},age:12})# Update age and favorite colorfrank_ref.update({age:13,"favorites.color":"Red"})
Dot notation allows you to update a single nested field without overwriting
other nested fields. If you update a nested field without dot notation, you will
overwrite the entire map field, as shown in the following example:
Web
// Create our initial docdb.collection("users").doc("frank").set({name:"Frank",favorites:{food:"Pizza",color:"Blue",subject:"Recess"},age:12}).then(function(){console.log("Frank created");});// Update the doc without using dot notation.// Notice the map value for favorites.db.collection("users").doc("frank").update({favorites:{food:"Ice Cream"}}).then(function(){console.log("Frank food updated");});/*EndingState,favorite.colorandfavorite.subjectarenolongerpresent:/users/frank{name:"Frank",favorites:{food:"Ice Cream",},age:12}*/
Update elements in an array
If your document contains an array field, you can usearrayUnion()andarrayRemove()to add and remove elements.arrayUnion()adds elements to an
array but only elements not already present.arrayRemove()removes all
instances of each given element.
Web
import{doc,updateDoc,arrayUnion,arrayRemove}from"firebase/firestore";constwashingtonRef=doc(db,"cities","DC");// Atomically add a new region to the "regions" array field.awaitupdateDoc(washingtonRef,{regions:arrayUnion("greater_virginia")});// Atomically remove a region from the "regions" array field.awaitupdateDoc(washingtonRef,{regions:arrayRemove("east_coast")});
varwashingtonRef=db.collection("cities").doc("DC");// Atomically add a new region to the "regions" array field.washingtonRef.update({regions:firebase.firestore.FieldValue.arrayUnion("greater_virginia")});// Atomically remove a region from the "regions" array field.washingtonRef.update({regions:firebase.firestore.FieldValue.arrayRemove("east_coast")});
Note:This product is not available on watchOS and App Clip targets.
letwashingtonRef=db.collection("cities").document("DC")// Atomically add a new region to the "regions" array field.washingtonRef.updateData(["regions":FieldValue.arrayUnion(["greater_virginia"])])// Atomically remove a region from the "regions" array field.washingtonRef.updateData(["regions":FieldValue.arrayRemove(["east_coast"])])
Note:This product is not available on watchOS and App Clip targets.
FIRDocumentReference*washingtonRef=[[self.dbcollectionWithPath:@"cities"]documentWithPath:@"DC"];// Atomically add a new region to the "regions" array field.[washingtonRefupdateData:@{@"regions":[FIRFieldValuefieldValueForArrayUnion:@[@"greater_virginia"]]}];// Atomically remove a new region to the "regions" array field.[washingtonRefupdateData:@{@"regions":[FIRFieldValuefieldValueForArrayRemove:@[@"east_coast"]]}];
valwashingtonRef=db.collection("cities").document("DC")// Atomically add a new region to the "regions" array field.washingtonRef.update("regions",FieldValue.arrayUnion("greater_virginia"))// Atomically remove a region from the "regions" array field.washingtonRef.update("regions",FieldValue.arrayRemove("east_coast"))
DocumentReferencewashingtonRef=db.collection("cities").document("DC");// Atomically add a new region to the "regions" array field.washingtonRef.update("regions",FieldValue.arrayUnion("greater_virginia"));// Atomically remove a region from the "regions" array field.washingtonRef.update("regions",FieldValue.arrayRemove("east_coast"));
finalwashingtonRef=db.collection("cities").doc("DC");// Atomically add a new region to the "regions" array field.washingtonRef.update({"regions":FieldValue.arrayUnion(["greater_virginia"]),});// Atomically remove a region from the "regions" array field.washingtonRef.update({"regions":FieldValue.arrayRemove(["east_coast"]),});
DocumentReferencewashingtonRef=db.collection("cities").document("DC");// Atomically add a new region to the "regions" array field.ApiFuture<WriteResult>arrayUnion=washingtonRef.update("regions",FieldValue.arrayUnion("greater_virginia"));System.out.println("Update time : "+arrayUnion.get());// Atomically remove a region from the "regions" array field.ApiFuture<WriteResult>arrayRm=washingtonRef.update("regions",FieldValue.arrayRemove("east_coast"));System.out.println("Update time : "+arrayRm.get());
city_ref=db.collection("cities").document("DC")# Atomically add a new region to the 'regions' array field.city_ref.update({"regions":firestore.ArrayUnion(["greater_virginia"])})# // Atomically remove a region from the 'regions' array field.city_ref.update({"regions":firestore.ArrayRemove(["east_coast"])})
city_ref=db.collection("cities").document("DC")# Atomically add a new region to the 'regions' array field.awaitcity_ref.update({"regions":firestore.ArrayUnion(["greater_virginia"])})# // Atomically remove a region from the 'regions' array field.awaitcity_ref.update({"regions":firestore.ArrayRemove(["east_coast"])})
// ...constwashingtonRef=db.collection('cities').doc('DC');// Atomically add a new region to the "regions" array field.constunionRes=awaitwashingtonRef.update({regions:FieldValue.arrayUnion('greater_virginia')});// Atomically remove a region from the "regions" array field.constremoveRes=awaitwashingtonRef.update({regions:FieldValue.arrayRemove('east_coast')});// To add or remove multiple items, pass multiple arguments to arrayUnion/arrayRemoveconstmultipleUnionRes=awaitwashingtonRef.update({regions:FieldValue.arrayUnion('south_carolina','texas')// Alternatively, you can use spread operator in ES6 syntax// const newRegions = ['south_carolina', 'texas']// regions: FieldValue.arrayUnion(...newRegions)});
$cityRef = $db->collection('samples/php/cities')->document('DC');// Atomically add a new region to the "regions" array field.$cityRef->update([['path' => 'regions', 'value' => FieldValue::arrayUnion(['greater_virginia'])]]);// Atomically remove a region from the "regions" array field.$cityRef->update([['path' => 'regions', 'value' => FieldValue::arrayRemove(['east_coast'])]]);
DocumentReferencewashingtonRef=db.Collection("cities").Document("DC");// Atomically add a new region to the "regions" array field.awaitwashingtonRef.UpdateAsync("Regions",FieldValue.ArrayUnion("greater_virginia"));// Atomically remove a region from the "regions" array field.awaitwashingtonRef.UpdateAsync("Regions",FieldValue.ArrayRemove("east_coast"));
You can increment or decrement a numeric field value as shown in the
following example. An increment operation increases or decreases the current
value of a field by the given amount.
Web
import{doc,updateDoc,increment}from"firebase/firestore";constwashingtonRef=doc(db,"cities","DC");// Atomically increment the population of the city by 50.awaitupdateDoc(washingtonRef,{population:increment(50)});
varwashingtonRef=db.collection('cities').doc('DC');// Atomically increment the population of the city by 50.washingtonRef.update({population:firebase.firestore.FieldValue.increment(50)});
Note:This product is not available on watchOS and App Clip targets.
letwashingtonRef=db.collection("cities").document("DC")// Atomically increment the population of the city by 50.// Note that increment() with no arguments increments by 1.washingtonRef.updateData(["population":FieldValue.increment(Int64(50))])
Note:This product is not available on watchOS and App Clip targets.
FIRDocumentReference*washingtonRef=[[self.dbcollectionWithPath:@"cities"]documentWithPath:@"DC"];// Atomically increment the population of the city by 50.// Note that increment() with no arguments increments by 1.[washingtonRefupdateData:@{@"population":[FIRFieldValuefieldValueForIntegerIncrement:50]}];
valwashingtonRef=db.collection("cities").document("DC")// Atomically increment the population of the city by 50.washingtonRef.update("population",FieldValue.increment(50))
DocumentReferencewashingtonRef=db.collection("cities").document("DC");// Atomically increment the population of the city by 50.washingtonRef.update("population",FieldValue.increment(50));
varwashingtonRef=db.collection('cities').doc('DC');// Atomically increment the population of the city by 50.washingtonRef.update({"population":FieldValue.increment(50)},);
DocumentReferencewashingtonRef=db.collection("cities").document("DC");// Atomically increment the population of the city by 50.finalApiFuture<WriteResult>updateFuture=washingtonRef.update("population",FieldValue.increment(50));
// ...constwashingtonRef=db.collection('cities').doc('DC');// Atomically increment the population of the city by 50.constres=awaitwashingtonRef.update({population:FieldValue.increment(50)});
import("context""fmt""cloud.google.com/go/firestore")// updateDocumentIncrement increments the population of the city document in the// cities collection by 50.funcupdateDocumentIncrement(projectID,citystring)error{// projectID := "my-project"ctx:=context.Background()client,err:=firestore.NewClient(ctx,projectID)iferr!=nil{returnfmt.Errorf("firestore.NewClient: %w",err)}deferclient.Close()dc:=client.Collection("cities").Doc(city)_,err=dc.Update(ctx,[]firestore.Update{{Path:"population",Value:firestore.Increment(50)},})iferr!=nil{returnfmt.Errorf("Update: %w",err)}returnnil}
$cityRef = $db->collection('samples/php/cities')->document('DC');// Atomically increment the population of the city by 50.$cityRef->update([['path' => 'regions', 'value' => FieldValue::increment(50)]]);
DocumentReferencewashingtonRef=db.Collection("cities").Document("DC");// Atomically increment the population of the city by 50.awaitwashingtonRef.UpdateAsync("Regions",FieldValue.Increment(50));
Increment operations are useful for implementing counters. Note that
updating a single document too quickly canlead to contention or errors. If you need to update
your counter at a very high rate, see theDistributed counterspage.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-04 UTC."],[],[],null,[]]