firestore: add data

Add Data to Cloud Firestore

There are several ways to write data to Cloud Firestore:

  • Set the data of a document within a collection, explicitly specifying a document identifier.
  • Add a new document to a collection. In this case, Cloud Firestore automatically generates the document identifier.
  • Create an empty document with an automatically generated identifier, and assign data to it later.

This guide explains how to use the set, add, or update individual documents in Cloud Firestore. If you want to write data in bulk, see Transactions and Batched Writes.

Note:  While the code samples cover multiple languages, the text explaining the samples refers to the Web method names.

Set a document

To create or overwrite a single document, use the set() method:

WEB
SWIFT
OBJECTIVE-C
ANDROID
JAVA
PYTHON
MORE
 
  
// Add a new document in collection "cities"
[[[ self . db collectionWithPath :@ "cities" ] documentWithPath :@ "LA" ] setData :@{
 
@ "name" : @ "Los Angeles" ,
 
@ "state" : @ "CA" ,
 
@ "country" : @ "USA"
} completion :^( NSError * _Nullable error ) {
 
if ( error != nil ) {
   
NSLog (@ "Error writing document: %@" , error );
 
} else {
   
NSLog (@ "Document successfully written!" );
 
}
}];
 

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:

WEB
SWIFT
OBJECTIVE-C
ANDROID
JAVA
PYTHON
MORE
 
  
// Write to the document reference, merging data with existing
// if the document already exists
[[[ self . db collectionWithPath :@ "cities" ] documentWithPath :@ "BJ" ]
     setData
:@{ @ "capital" : @YES }
     options
:[ FIRSetOptions merge ]
     completion
:^( NSError * _Nullable error ) {
       
// ...
     
}];
 

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.

Data types

Cloud Firestore lets you write a variety of data types inside a document, including strings, booleans, numbers, dates, null, and nested arrays and objects. Cloud Firestore always stores numbers as doubles, regardless of what type of number you use in your code.

WEB
SWIFT
OBJECTIVE-C
ANDROID
JAVA
PYTHON
MORE
 
  
NSDictionary * docData = @{
 
@ "stringExample" : @ "Hello world!" ,
 
@ "booleanExample" : @YES ,
 
@ "numberExample" : @ 3.14 ,
 
@ "dateExample" : [ NSDate date ],
 
@ "arrayExample" : @[@ 5 , @YES , @ "hello" ],
 
@ "nullExample" : [ NSNull null ],
 
@ "objectExample" : @{
   
@ "a" : @ 5 ,
   
@ "b" : @{
     
@ "nested" : @ "foo"
   
}
 
}
};

[[[ self . db collectionWithPath :@ "data" ] documentWithPath :@ "one" ] setData : docData
    completion
:^( NSError * _Nullable error ) {
     
if ( error != nil ) {
       
NSLog (@ "Error writing document: %@" , error );
     
} else {
       
NSLog (@ "Document successfully written!" );
     
}
   
}];
 

Custom objects

Using Java Map objects to represent your documents is often not very convenient, so Cloud Firestore also supports writing your own Java objects with custom classes. Cloud Firestore will internally convert the objects to supported data types.

Important:  Each custom class must have a public constructor that takes no arguments. In addition, the class must include a public getter for each property.

Using custom classes, you could rewrite the initial example as follows:

WEB
SWIFT
OBJECTIVE-C
ANDROID
JAVA
PYTHON
MORE
 
  
// This isn't supported in Objective-C.
 
WEB
SWIFT
OBJECTIVE-C
ANDROID
JAVA
PYTHON
MORE
 
  
// This isn't supported in Objective-C.
 

Add a document

When you use set() to create a document, you must specify an ID for the document to create. For example:

WEB
SWIFT
OBJECTIVE-C
ANDROID
JAVA
PYTHON
MORE
 
  
[[[ self . db collectionWithPath :@ "cities" ] documentWithPath :@ "new-city-id" ]
    setData
: data ];
 

But sometimes there isn't a meaningful ID for the document, and it's more convenient to let Cloud Firestore auto-generate an ID for you. You can do this by calling add():

WEB
SWIFT
OBJECTIVE-C
ANDROID
JAVA
PYTHON
MORE
 
  
// Add a new document with a generated id.
__block
FIRDocumentReference * ref =
   
[[ self . db collectionWithPath :@ "cities" ] addDocumentWithData :@{
     
@ "name" : @ "Tokyo" ,
     
@ "country" : @ "Japan"
   
} completion :^( NSError * _Nullable error ) {
     
if ( error != nil ) {
       
NSLog (@ "Error adding document: %@" , error );
     
} else {
       
NSLog (@ "Document added with ID: %@" , ref . documentID );
     
}
   
}];
 
Important:  Unlike "push IDs" in the Firebase Realtime Database, Cloud Firestore auto-generated IDs do not provide any automatic ordering. If you want to be able to order your documents by creation date, you should store a timestamp as a field in the documents.

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 call doc():

WEB
SWIFT
OBJECTIVE-C
ANDROID
JAVA
PYTHON
MORE
 
  
FIRDocumentReference * newCityRef = [[ self . db collectionWithPath :@ "cities" ] documentWithAutoID ];
// later...
[ newCityRef setData :@{ /* ... */ }];
 

Behind the scenes, .add(...) and .doc().set(...) are completely equivalent, so you can use whichever is more convenient.

Update a document

To update some fields of a document without overwriting the entire document, use the update()method:

WEB
SWIFT
OBJECTIVE-C
ANDROID
JAVA
PYTHON
MORE
 
  
FIRDocumentReference * washingtonRef =
   
[[ self . db collectionWithPath :@ "cities" ] documentWithPath :@ "DC" ];
// Set the "capital" field of the city
[ washingtonRef updateData :@{
 
@ "capital" : @YES
} completion :^( NSError * _Nullable error ) {
 
if ( error != nil ) {
   
NSLog (@ "Error updating document: %@" , error );
 
} else {
   
NSLog (@ "Document successfully updated" );
 
}
}];
 

Update fields in nested objects

If your document contains nested objects, you can use "dot notation" to reference nested fields within the document when you call update():

WEB
SWIFT
OBJECTIVE-C
ANDROID
JAVA
PYTHON
MORE
 
  
// Create an initial document to update.
FIRDocumentReference * frankDocRef =
   
[[ self . db collectionWithPath :@ "users" ] documentWithPath :@ "frank" ];
[ frankDocRef setData :@{
 
@ "name" : @ "Frank" ,
 
@ "favorites" : @{
   
@ "food" : @ "Pizza" ,
   
@ "color" : @ "Blue" ,
   
@ "subject" : @ "recess"
 
},
 
@ "age" : @ 12
}];
// To update age and favorite color:
[ frankDocRef updateData :@{
 
@ "age" : @ 13 ,
 
@ "favorites.color" : @ "Red" ,
} completion :^( NSError * _Nullable error ) {
 
if ( error != nil ) {
   
NSLog (@ "Error updating document: %@" , error );
 
} else {
   
NSLog (@ "Document successfully updated" );
 
}
}];
 

You can also add server timestamps to specific fields in your documents, to track when an update was received by the server:

WEB
SWIFT
OBJECTIVE-C
ANDROID
JAVA
PYTHON
MORE
 
  
[[[ self . db collectionWithPath :@ "objects" ] documentWithPath :@ "some-id" ] updateData :@{
 
@ "lastUpdated" : [ FIRFieldValue fieldValueForServerTimestamp ]
} completion :^( NSError * _Nullable error ) {
 
if ( error != nil ) {
   
NSLog (@ "Error updating document: %@" , error );
 
} else {
   
NSLog (@ "Document successfully updated" );
 
}
}];
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值