添加和更新数据
本文档介绍了如何在 Firestore 中设置、添加或更新单个文档。如需批量写入数据,请参阅事务和批量写入。
概览
您可以通过以下任一方式将数据写入 Firestore:
- 设置集合中的文档的数据,明确指定文档标识符。
- 向集合添加新文档。在这种情况下,Firestore 会自动生成文档标识符。
- 创建一个使用自动生成的标识符的空文档,并在以后向该文档分配数据。
准备工作
在初始化 Firestore 以设置、添加或更新数据之前,您必须完成以下步骤:
- 创建 Firestore 数据库。如需了解详情,请参阅 Firestore 快速入门之一。
- 如果您使用的是 Web 或移动客户端库,请使用安全规则进行身份验证。如需了解详情,请参阅安全规则使用入门。
- 如果您使用的是服务器客户端库或 REST API,请使用 Identity and Access Management (IAM) 进行身份验证。如需了解详情,请参阅服务器客户端库的安全性。
初始化 Firestore
初始化 Firestore 的实例:
Web 版本 9
import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore"; // TODO: Replace the following with your app's Firebase project configuration // See: https://support.google.com/firebase/answer/7015592 const firebaseConfig = { FIREBASE_CONFIGURATION }; // Initialize Firebase const app = initializeApp(firebaseConfig); // Initialize Firestore and get a reference to the service const db = getFirestore(app);
将 FIREBASE_CONFIGURATION 替换为 Web 应用的 firebaseConfig
。
如需在设备的网络连接中断时保留数据,请参阅启用离线数据文档。
Web 版本 8
import firebase from "firebase/app"; import "firebase/firestore"; // TODO: Replace the following with your app's Firebase project configuration // See: https://support.google.com/firebase/answer/7015592 const firebaseConfig = { FIREBASE_CONFIGURATION }; // Initialize Firebase firebase.initializeApp(firebaseConfig); // Initialize Firestore and get a reference to the service const db = firebase.firestore();
将 FIREBASE_CONFIGURATION 替换为 Web 应用的 firebaseConfig
。
如需在设备的网络连接中断时保留数据,请参阅启用离线数据文档。
Swift
import FirebaseCore import FirebaseFirestore
FirebaseApp.configure() let db = Firestore.firestore()
Objective-C
@import FirebaseCore; @import FirebaseFirestore; // Use Firebase library to configure APIs [FIRApp configure];
FIRFirestore *defaultFirestore = [FIRFirestore firestore];
Kotlin
Android
// Access a Firestore instance from your Activity
val db = Firebase.firestore
Java
Android
// Access a Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();
Dart
db = FirebaseFirestore.instance;
Java
import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.FirestoreOptions;
Python
from google.cloud import firestore # The `project` 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 = firestore.Client(project="my-project-id")
Python
(异步)
from google.cloud import firestore # The `project` 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 = firestore.AsyncClient(project="my-project-id")
C++
// Make sure the call to `Create()` happens some time before you call Firestore::GetInstance(). App::Create(); Firestore* db = Firestore::GetInstance();
Node.js
const Firestore = require('@google-cloud/firestore'); const db = new Firestore({ projectId: 'YOUR_PROJECT_ID', keyFilename: '/path/to/keyfile.json', });
Go
PHP
PHP
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Unity
using Firebase.Firestore; using Firebase.Extensions;
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
C#
C#
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Ruby
设置文档
如需创建或覆盖单个文档,请使用以下特定于语言的 set()
方法:
Web 版本 9
使用 setDoc()
方法:
import { doc, setDoc } from "firebase/firestore"; // Add a new document in collection "cities" await setDoc(doc(db, "cities", "LA"), { name: "Los Angeles", state: "CA", country: "USA" });
Web 版本 8
使用 set()
方法:
// 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); });
Swift
使用 setData()
方法:
// Add a new document in collection "cities" do { try await db.collection("cities").document("LA").setData([ "name": "Los Angeles", "state": "CA", "country": "USA" ]) print("Document successfully written!") } catch { print("Error writing document: \(error)") }
Objective-C
使用 setData:
方法:
// 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!"); } }];
Kotlin
Android
使用 set()
方法:
val city = hashMapOf( "name" to "Los Angeles", "state" to "CA", "country" to "USA", ) db.collection("cities").document("LA") .set(city) .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") } .addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) }
Java
Android
使用 set()
方法:
Map<String, Object> city = new HashMap<>(); city.put("name", "Los Angeles"); city.put("state", "CA"); city.put("country", "USA"); db.collection("cities").document("LA") .set(city) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d(TAG, "DocumentSnapshot successfully written!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error writing document", e); } });
Dart
使用 set()
方法:
final city = <String, String>{ "name": "Los Angeles", "state": "CA", "country": "USA" }; db .collection("cities") .doc("LA") .set(city) .onError((e, _) => print("Error writing document: $e"));
Java
使用 set()
方法:
Python
使用 set()
方法:
Python
(异步)
使用 set()
方法:
C++
使用 Set()
方法:
// Add a new document in collection 'cities' db->Collection("cities") .Document("LA") .Set({{"name", FieldValue::String("Los Angeles")}, {"state", FieldValue::String("CA")}, {"country", FieldValue::String("USA")}}) .OnCompletion([](const Future<void>& future) { if (future.error() == Error::kErrorOk) { std::cout << "DocumentSnapshot successfully written!" << std::endl; } else { std::cout << "Error writing document: " << future.error_message() << std::endl; } });
Node.js
使用 set()
方法:
Go
使用 Set()
方法:
PHP
使用 set()
方法:
PHP
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Unity
使用 SetAsync()
方法:
DocumentReference docRef = db.Collection("cities").Document("LA"); Dictionary<string, object> city = new Dictionary<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."); });
C#
使用 SetAsync()
方法:
Ruby
使用 set()
方法:
如果文档不存在,系统将会创建一个。如果文档存在,其内容将被新提供的数据覆盖,除非您指定应将该数据合并到现有文档中,如下所示:
Web 版本 9
import { doc, setDoc } from "firebase/firestore"; const cityRef = doc(db, 'cities', 'BJ'); setDoc(cityRef, { capital: true }, { merge: true });
Web 版本 8
var cityRef = db.collection('cities').doc('BJ'); var setWithMerge = cityRef.set({ capital: true }, { merge: true });
Swift
// Update one field, creating the document if it does not exist. db.collection("cities").document("BJ").setData([ "capital": true ], merge: true)
Objective-C
// Write to the document reference, merging data with existing // if the document already exists [[[self.db collectionWithPath:@"cities"] documentWithPath:@"BJ"] setData:@{ @"capital": @YES } merge:YES completion:^(NSError * _Nullable error) { // ... }];
Kotlin
Android
// Update one field, creating the document if it does not already exist. val data = hashMapOf("capital" to true) db.collection("cities").document("BJ") .set(data, SetOptions.merge())
Java
Android
// Update one field, creating the document if it does not already exist. Map<String, Object> data = new HashMap<>(); data.put("capital", true); db.collection("cities").document("BJ") .set(data, SetOptions.merge());
Dart
// Update one field, creating the document if it does not already exist. final data = {"capital": true}; db.collection("cities").doc("BJ").set(data, SetOptions(merge: true));
Java
Python
Python
(异步)
C++
db->Collection("cities").Document("BJ").Set( {{"capital", FieldValue::Boolean(true)}}, SetOptions::Merge());
Node.js
Go
PHP
PHP
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Unity
DocumentReference docRef = db.Collection("cities").Document("LA"); Dictionary<string, object> update = new Dictionary<string, object> { { "capital", false } }; docRef.SetAsync(update, SetOptions.MergeAll);
C#
Ruby
如果您不确定文档是否存在,请传递相应选项,指明应将新数据与任何现有文档合并,以避免覆盖整个文档。对于包含映射的文档,如果您使用包含空映射的字段来指定其内容,则系统会覆盖目标文档的映射字段。
数据类型
Firestore 允许您在文档中写入各种类型的数据,包括字符串、布尔值、数字、日期、null 以及嵌套的数组和对象。无论您在代码中使用哪种类型的数字,Firestore 都会将数字存储为双精度型数字。
Web 版本 9
import { doc, setDoc, Timestamp } from "firebase/firestore"; const docData = { stringExample: "Hello world!", booleanExample: true, numberExample: 3.14159265, dateExample: Timestamp.fromDate(new Date("December 10, 1815")), arrayExample: [5, true, "hello"], nullExample: null, objectExample: { a: 5, b: { nested: "foo" } } }; await setDoc(doc(db, "data", "one"), docData);
Web 版本 8
var docData = { stringExample: "Hello world!", booleanExample: true, numberExample: 3.14159265, dateExample: firebase.firestore.Timestamp.fromDate(new Date("December 10, 1815")), arrayExample: [5, true, "hello"], nullExample: null, objectExample: { a: 5, b: { nested: "foo" } } }; db.collection("data").doc("one").set(docData).then(() => { console.log("Document successfully written!"); });
Swift
let docData: [String: Any] = [ "stringExample": "Hello world!", "booleanExample": true, "numberExample": 3.14159265, "dateExample": Timestamp(date: Date()), "arrayExample": [5, true, "hello"], "nullExample": NSNull(), "objectExample": [ "a": 5, "b": [ "nested": "foo" ] ] ] do { try await db.collection("data").document("one").setData(docData) print("Document successfully written!") } catch { print("Error writing document: \(error)") }
Objective-C
NSDictionary *docData = @{ @"stringExample": @"Hello world!", @"booleanExample": @YES, @"numberExample": @3.14, @"dateExample": [FIRTimestamp timestampWithDate:[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!"); } }];
Kotlin
Android
val docData = hashMapOf( "stringExample" to "Hello world!", "booleanExample" to true, "numberExample" to 3.14159265, "dateExample" to Timestamp(Date()), "listExample" to arrayListOf(1, 2, 3), "nullExample" to null, ) val nestedData = hashMapOf( "a" to 5, "b" to true, ) docData["objectExample"] = nestedData db.collection("data").document("one") .set(docData) .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") } .addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) }
Java
Android
Map<String, Object> docData = new HashMap<>(); docData.put("stringExample", "Hello world!"); docData.put("booleanExample", true); docData.put("numberExample", 3.14159265); docData.put("dateExample", new Timestamp(new Date())); docData.put("listExample", Arrays.asList(1, 2, 3)); docData.put("nullExample", null); Map<String, Object> nestedData = new HashMap<>(); nestedData.put("a", 5); nestedData.put("b", true); docData.put("objectExample", nestedData); db.collection("data").document("one") .set(docData) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d(TAG, "DocumentSnapshot successfully written!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error writing document", e); } });
Dart
final docData = { "stringExample": "Hello world!", "booleanExample": true, "numberExample": 3.14159265, "dateExample": Timestamp.now(), "listExample": [1, 2, 3], "nullExample": null }; final nestedData = { "a": 5, "b": true, }; docData["objectExample"] = nestedData; db .collection("data") .doc("one") .set(docData) .onError((e, _) => print("Error writing document: $e"));
Java
Python
Python
(异步)
C++
MapFieldValue doc_data{ {"stringExample", FieldValue::String("Hello world!")}, {"booleanExample", FieldValue::Boolean(true)}, {"numberExample", FieldValue::Double(3.14159265)}, {"dateExample", FieldValue::Timestamp(Timestamp::Now())}, {"arrayExample", FieldValue::Array({FieldValue::Integer(1), FieldValue::Integer(2), FieldValue::Integer(3)})}, {"nullExample", FieldValue::Null()}, {"objectExample", FieldValue::Map( {{"a", FieldValue::Integer(5)}, {"b", FieldValue::Map( {{"nested", FieldValue::String("foo")}})}})}, }; db->Collection("data").Document("one").Set(doc_data).OnCompletion( [](const Future<void>& future) { if (future.error() == Error::kErrorOk) { std::cout << "DocumentSnapshot successfully written!" << std::endl; } else { std::cout << "Error writing document: " << future.error_message() << std::endl; } });
Node.js
Go
PHP
PHP
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Unity
DocumentReference docRef = db.Collection("data").Document("one"); Dictionary<string, object> docData = new Dictionary<string, object> { { "stringExample", "Hello World" }, { "booleanExample", false }, { "numberExample", 3.14159265 }, { "nullExample", null }, { "arrayExample", new List<object>() { 5, true, "Hello" } }, { "objectExample", new Dictionary<string, object> { { "a", 5 }, { "b", true }, } }, }; docRef.SetAsync(docData);
C#
Ruby
自定义对象
使用 Map
或 Dictionary
对象来表示文档通常不太方便,因此 Firestore 支持使用自定义类写入文档。Firestore 会将对象转换为受支持的数据类型。
使用自定义类,您可以按如下方式重写初始示例:
Web 版本 9
class City { constructor (name, state, country ) { this.name = name; this.state = state; this.country = country; } toString() { return this.name + ', ' + this.state + ', ' + this.country; } } // Firestore data converter const cityConverter = { toFirestore: (city) => { return { name: city.name, state: city.state, country: city.country }; }, fromFirestore: (snapshot, options) => { const data = snapshot.data(options); return new City(data.name, data.state, data.country); } };
Web 版本 8
class City { constructor (name, state, country ) { this.name = name; this.state = state; this.country = country; } toString() { return this.name + ', ' + this.state + ', ' + this.country; } } // Firestore data converter var cityConverter = { toFirestore: function(city) { return { name: city.name, state: city.state, country: city.country }; }, fromFirestore: function(snapshot, options){ const data = snapshot.data(options); return new City(data.name, data.state, data.country); } };
Swift
public struct City: Codable { let name: String let state: String? let country: String? let isCapital: Bool? let population: Int64? enum CodingKeys: String, CodingKey { case name case state case country case isCapital = "capital" case population } }
Objective-C
// This isn't supported in Objective-C.
Kotlin
Android
data class City( val name: String? = null, val state: String? = null, val country: String? = null, @field:JvmField // use this annotation if your Boolean field is prefixed with 'is' val isCapital: Boolean? = null, val population: Long? = null, val regions: List<String>? = null, )
Java
Android
每个自定义类都必须有一个不接受任何参数的公共构造函数。此外,类必须为每个属性包含一个公共 getter。
public class City { private String name; private String state; private String country; private boolean capital; private long population; private List<String> regions; public City() {} public City(String name, String state, String country, boolean capital, long population, List<String> regions) { // ... } public String getName() { return name; } public String getState() { return state; } public String getCountry() { return country; } public boolean isCapital() { return capital; } public long getPopulation() { return population; } public List<String> getRegions() { return regions; } }
Dart
class City { final String? name; final String? state; final String? country; final bool? capital; final int? population; final List<String>? regions; City({ this.name, this.state, this.country, this.capital, this.population, this.regions, }); factory City.fromFirestore( DocumentSnapshot<Map<String, dynamic>> snapshot, SnapshotOptions? options, ) { final data = snapshot.data(); return City( name: data?['name'], state: data?['state'], country: data?['country'], capital: data?['capital'], population: data?['population'], regions: data?['regions'] is Iterable ? List.from(data?['regions']) : null, ); } Map<String, dynamic> toFirestore() { return { if (name != null) "name": name, if (state != null) "state": state, if (country != null) "country": country, if (capital != null) "capital": capital, if (population != null) "population": population, if (regions != null) "regions": regions, }; } }
Java
Python
Python
(异步)
C++
// This is not yet supported.
Node.js
// Node.js uses JavaScript objects
Go
PHP
PHP
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Unity
[FirestoreData] public class City { [FirestoreProperty] public string Name { get; set; } [FirestoreProperty] public string State { get; set; } [FirestoreProperty] public string Country { get; set; } [FirestoreProperty] public bool Capital { get; set; } [FirestoreProperty] public long Population { get; set; } }
C#
Ruby
// This isn't supported in Ruby
Web 版本 9
import { doc, setDoc } from "firebase/firestore"; // Set with cityConverter const ref = doc(db, "cities", "LA").withConverter(cityConverter); await setDoc(ref, new City("Los Angeles", "CA", "USA"));
Web 版本 8
// Set with cityConverter db.collection("cities").doc("LA") .withConverter(cityConverter) .set(new City("Los Angeles", "CA", "USA"));
Swift
let city = City(name: "Los Angeles", state: "CA", country: "USA", isCapital: false, population: 5000000) do { try db.collection("cities").document("LA").setData(from: city) } catch let error { print("Error writing city to Firestore: \(error)") }
Objective-C
// This isn't supported in Objective-C.
Kotlin
Android
val city = City( "Los Angeles", "CA", "USA", false, 5000000L, listOf("west_coast", "socal"), ) db.collection("cities").document("LA").set(city)
Java
Android
City city = new City("Los Angeles", "CA", "USA", false, 5000000L, Arrays.asList("west_coast", "sorcal")); db.collection("cities").document("LA").set(city);
Dart
final city = City( name: "Los Angeles", state: "CA", country: "USA", capital: false, population: 5000000, regions: ["west_coast", "socal"], ); final docRef = db .collection("cities") .withConverter( fromFirestore: City.fromFirestore, toFirestore: (City city, options) => city.toFirestore(), ) .doc("LA"); await docRef.set(city);
Java
Python
Python
(异步)
C++
// This is not yet supported.
Node.js
// Node.js uses JavaScript objects
Go
PHP
// This isn't supported in PHP.
Unity
DocumentReference docRef = db.Collection("cities").Document("LA"); City city = new City { Name = "Los Angeles", State = "CA", Country = "USA", Capital = false, Population = 3900000L }; docRef.SetAsync(city);
C#
Ruby
// This isn't supported in Ruby.
添加文档
当您使用 set()
创建文档时,必须为要创建的文档指定 ID,如以下示例所示:
Web 版本 9
import { doc, setDoc } from "firebase/firestore"; await setDoc(doc(db, "cities", "new-city-id"), data);
Web 版本 8
db.collection("cities").doc("new-city-id").set(data);
Swift
db.collection("cities").document("new-city-id").setData(data)
Objective-C
[[[self.db collectionWithPath:@"cities"] documentWithPath:@"new-city-id"] setData:data];
Kotlin
Android
db.collection("cities").document("new-city-id").set(data)
Java
Android
db.collection("cities").document("new-city-id").set(data);
Dart
db.collection("cities").doc("new-city-id").set({"name": "Chicago"});
Java
Python
Python
(异步)
C++
db->Collection("cities").Document("SF").Set({/*some data*/});
Node.js
Go
PHP
PHP
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Unity
db.Collection("cities").Document("new-city-id").SetAsync(city);
C#
Ruby
如果无法为文档指定有意义的 ID,Firestore 可为您自动生成 ID。您可以调用以下特定于语言的 add()
方法:
Web 版本 9
使用 addDoc()
方法:
import { collection, addDoc } from "firebase/firestore"; // Add a new document with a generated id. const docRef = await addDoc(collection(db, "cities"), { name: "Tokyo", country: "Japan" }); console.log("Document written with ID: ", docRef.id);
Web 版本 8
使用 add()
方法:
// 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); });
Swift
使用 addDocument()
方法:
// Add a new document with a generated id. do { let ref = try await db.collection("cities").addDocument(data: [ "name": "Tokyo", "country": "Japan" ]) print("Document added with ID: \(ref.documentID)") } catch { print("Error adding document: \(error)") }
Objective-C
使用 addDocumentWithData:
方法:
// 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); } }];
Kotlin
Android
使用 add()
方法:
// Add a new document with a generated id. val data = 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) }
Java
Android
使用 add()
方法:
// Add a new document with a generated id. Map<String, Object> data = new HashMap<>(); data.put("name", "Tokyo"); data.put("country", "Japan"); db.collection("cities") .add(data) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } });
Dart
使用 add()
方法:
// Add a new document with a generated id. final data = {"name": "Tokyo", "country": "Japan"}; db.collection("cities").add(data).then((documentSnapshot) => print("Added Data with ID: ${documentSnapshot.id}"));
Java
使用 add()
方法:
Python
使用 add()
方法:
Python
(异步)
使用 add()
方法:
C++
使用 Add()
方法:
db->Collection("cities").Add({/*some data*/});
Node.js
使用 add()
方法:
Go
使用 Add()
方法:
PHP
使用 add()
方法:
PHP
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Unity
使用 AddAsync()
方法:
Dictionary<string, object> city = new Dictionary<string, object> { { "Name", "Tokyo" }, { "Country", "Japan" } }; db.Collection("cities").AddAsync(city).ContinueWithOnMainThread(task => { DocumentReference addedDocRef = task.Result; Debug.Log(String.Format("Added document with ID: {0}.", addedDocRef.Id)); });
C#
使用 AddAsync()
方法:
Ruby
使用 add()
方法:
在某些情况下,创建含自动生成的 ID 的文档引用并在以后使用,是一种很有用的做法。对于此使用场景,您可以按如下方式调用 doc()
:
Web 版本 9
import { collection, doc, setDoc } from "firebase/firestore"; // Add a new document with a generated id const newCityRef = doc(collection(db, "cities")); // later... await setDoc(newCityRef, data);
Web 版本 8
// Add a new document with a generated id. var newCityRef = db.collection("cities").doc(); // later... newCityRef.set(data);
Swift
let newCityRef = db.collection("cities").document() // later... newCityRef.setData([ // ... ])
Objective-C
FIRDocumentReference *newCityRef = [[self.db collectionWithPath:@"cities"] documentWithAutoID]; // later... [newCityRef setData:@{ /* ... */ }];
Kotlin
Android
val data = HashMap<String, Any>() val newCityRef = db.collection("cities").document() // Later... newCityRef.set(data)
Java
Android
Map<String, Object> data = new HashMap<>(); DocumentReference newCityRef = db.collection("cities").document(); // Later... newCityRef.set(data);
Dart
// Add a new document with a generated id. final data = <String, dynamic>{}; final newCityRef = db.collection("cities").doc(); // Later... newCityRef.set(data);
Java
Python
Python
(异步)
C++
DocumentReference new_city_ref = db->Collection("cities").Document();
Node.js
Go
PHP
PHP
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Unity
DocumentReference addedDocRef = 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#
Ruby
在后端,.add(...)
和 .doc().set(...)
是等效的,因此您可以使用任一选项。
更新文档
如需更新文档的某些字段而不覆盖整个文档,请使用以下特定于语言的 update()
方法:
Web 版本 9
使用 updateDoc()
方法:
import { doc, updateDoc } from "firebase/firestore"; const washingtonRef = doc(db, "cities", "DC"); // Set the "capital" field of the city 'DC' await updateDoc(washingtonRef, { capital: true });
Web 版本 8
使用 update()
方法:
var washingtonRef = db.collection("cities").doc("DC"); // Set the "capital" field of the city 'DC' return washingtonRef.update({ capital: true }) .then(() => { console.log("Document successfully updated!"); }) .catch((error) => { // The document probably doesn't exist. console.error("Error updating document: ", error); });
Swift
使用 updateData()
方法:
let washingtonRef = db.collection("cities").document("DC") // Set the "capital" field of the city 'DC' do { try await washingtonRef.updateData([ "capital": true ]) print("Document successfully updated") } catch { print("Error updating document: \(error)") }
Objective-C
使用 updateData:
方法:
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"); } }];
Kotlin
Android
使用 update()
方法:
val washingtonRef = 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) }
Java
Android
使用 update()
方法:
DocumentReference washingtonRef = db.collection("cities").document("DC"); // Set the "isCapital" field of the city 'DC' washingtonRef .update("capital", true) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d(TAG, "DocumentSnapshot successfully updated!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error updating document", e); } });
Dart
使用 update()
方法:
final washingtonRef = db.collection("cites").doc("DC"); washingtonRef.update({"capital": true}).then( (value) => print("DocumentSnapshot successfully updated!"), onError: (e) => print("Error updating document $e"));
Java
使用 update()
方法:
Python
使用 update()
方法:
Python
(异步)
使用 update()
方法:
C++
使用 Update()
方法:
DocumentReference washington_ref = db->Collection("cities").Document("DC"); // Set the "capital" field of the city "DC". washington_ref.Update({{"capital", FieldValue::Boolean(true)}});
Node.js
使用 update()
方法:
Go
使用 Update()
方法:
PHP
使用 update()
方法:
PHP
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Unity
使用 UpdateAsync()
方法:
DocumentReference cityRef = db.Collection("cities").Document("new-city-id"); Dictionary<string, object> updates = new Dictionary<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#
使用 UpdateAsync()
方法:
Ruby
使用 update()
方法:
服务器时间戳
您可以将文档中的字段设置为服务器时间戳,以跟踪服务器何时接收更新。
Web 版本 9
import { updateDoc, serverTimestamp } from "firebase/firestore"; const docRef = doc(db, 'objects', 'some-id'); // Update the timestamp field with the value from the server const updateTimestamp = await updateDoc(docRef, { timestamp: serverTimestamp() });
Web 版本 8
var docRef = db.collection('objects').doc('some-id'); // Update the timestamp field with the value from the server var updateTimestamp = docRef.update({ timestamp: firebase.firestore.FieldValue.serverTimestamp() });
Swift
do { try await db.collection("objects").document("some-id").updateData([ "lastUpdated": FieldValue.serverTimestamp(), ]) print("Document successfully updated") } catch { print("Error updating document: \(error)") }
Objective-C
[[[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"); } }];
Kotlin
Android
// 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. val docRef = db.collection("objects").document("some-id") // Update the timestamp field with the value from the server val updates = hashMapOf<String, Any>( "timestamp" to FieldValue.serverTimestamp(), ) docRef.update(updates).addOnCompleteListener { }
Java
Android
// 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. DocumentReference docRef = db.collection("objects").document("some-id"); // Update the timestamp field with the value from the server Map<String,Object> updates = new HashMap<>(); updates.put("timestamp", FieldValue.serverTimestamp()); docRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() { // ... // ...
Dart
final docRef = db.collection("objects").doc("some-id"); final updates = <String, dynamic>{ "timestamp": FieldValue.serverTimestamp(), }; docRef.update(updates).then( (value) => print("DocumentSnapshot successfully updated!"), onError: (e) => print("Error updating document $e"));
Java
Python
Python
(异步)
C++
DocumentReference doc_ref = db->Collection("objects").Document("some-id"); doc_ref.Update({{"timestamp", FieldValue::ServerTimestamp()}}) .OnCompletion([](const Future<void>& future) { // ... });
Node.js
Go
PHP
PHP
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Unity
DocumentReference cityRef = 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."); });
C#
Ruby
更新事务中的多个时间戳字段时,每个字段都会获得相同的服务器时间戳值。
更新嵌套对象中的字段
如果您的文档包含嵌套对象,可以在调用 update()
时使用“点表示法”来引用文档中的嵌套字段:
Web 版本 9
import { doc, setDoc, updateDoc } from "firebase/firestore"; // Create an initial document to update. const frankDocRef = doc(db, "users", "frank"); await setDoc(frankDocRef, { name: "Frank", favorites: { food: "Pizza", color: "Blue", subject: "recess" }, age: 12 }); // To update age and favorite color: await updateDoc(frankDocRef, { "age": 13, "favorites.color": "Red" });
Web 版本 8
// Create an initial document to update. var frankDocRef = 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!"); });
Swift
// Create an initial document to update. let frankDocRef = db.collection("users").document("frank") do { try await frankDocRef.setData([ "name": "Frank", "favorites": [ "food": "Pizza", "color": "Blue", "subject": "recess" ], "age": 12 ]) // To update age and favorite color: try await frankDocRef.updateData([ "age": 13, "favorites.color": "Red" ]) print("Document successfully updated") } catch { print("Error updating document: \(error)") }
Objective-C
// 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"); } }];
Kotlin
Android
// Assume the document contains: // { // name: "Frank", // favorites: { food: "Pizza", color: "Blue", subject: "recess" } // age: 12 // } // // To update age and favorite color: db.collection("users").document("frank") .update( mapOf( "age" to 13, "favorites.color" to "Red", ), )
Java
Android
// Assume the document contains: // { // name: "Frank", // favorites: { food: "Pizza", color: "Blue", subject: "recess" } // age: 12 // } // // To update age and favorite color: db.collection("users").document("frank") .update( "age", 13, "favorites.color", "Red" );
Dart
// Assume the document contains: // { // name: "Frank", // favorites: { food: "Pizza", color: "Blue", subject: "recess" } // age: 12 // } db .collection("users") .doc("frank") .update({"age": 13, "favorites.color": "Red"});
Java
Python
Python
(异步)
C++
// Assume the document contains: // { // name: "Frank", // favorites: { food: "Pizza", color: "Blue", subject: "recess" } // age: 12 // } // // To update age and favorite color: db->Collection("users").Document("frank").Update({ {"age", FieldValue::Integer(13)}, {"favorites.color", FieldValue::String("red")}, });
Node.js
Go
PHP
PHP
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Unity
DocumentReference frankDocRef = db.Collection("users").Document("frank"); Dictionary<string, object> initialData = new Dictionary<string, object> { { "Name", "Frank" }, { "Age", 12 } }; Dictionary<string, object> favorites = new Dictionary<string, object> { { "Food", "Pizza" }, { "Color", "Blue" }, { "Subject", "Recess" }, }; initialData.Add("Favorites", favorites); frankDocRef.SetAsync(initialData).ContinueWithOnMainThread(task => { // Update age and favorite color Dictionary<string, object> updates = new Dictionary<string, object> { { "Age", 13 }, { "Favorites.Color", "Red" }, }; // Asynchronously update the document return frankDocRef.UpdateAsync(updates); }).ContinueWithOnMainThread(task => { Debug.Log( "Updated the age and favorite color fields of the Frank document in " + "the users collection."); });
C#
Ruby
借助点表示法,您可以更新单个嵌套字段,而不覆盖其他嵌套字段。如果您没有使用点表示法来更新嵌套字段,则将覆盖整个映射字段,如以下示例所示:
Web
// Create our initial doc db.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"); }); /* Ending State, favorite.color and favorite.subject are no longer present: /users /frank { name: "Frank", favorites: { food: "Ice Cream", }, age: 12 } */
更新数组中的元素
如果文档包含数组字段,您可以使用 arrayUnion()
和 arrayRemove()
添加和移除元素。arrayUnion()
可用于向数组添加元素,但只能添加不存在的元素。arrayRemove()
可用于删除每个指定元素的所有实例。
Web 版本 9
import { doc, updateDoc, arrayUnion, arrayRemove } from "firebase/firestore"; const washingtonRef = doc(db, "cities", "DC"); // Atomically add a new region to the "regions" array field. await updateDoc(washingtonRef, { regions: arrayUnion("greater_virginia") }); // Atomically remove a region from the "regions" array field. await updateDoc(washingtonRef, { regions: arrayRemove("east_coast") });
Web 版本 8
var washingtonRef = 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") });
Swift
let washingtonRef = 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"]) ])
Objective-C
FIRDocumentReference *washingtonRef = [[self.db collectionWithPath:@"cities"] documentWithPath:@"DC"]; // Atomically add a new region to the "regions" array field. [washingtonRef updateData:@{ @"regions": [FIRFieldValue fieldValueForArrayUnion:@[@"greater_virginia"]] }]; // Atomically remove a new region to the "regions" array field. [washingtonRef updateData:@{ @"regions": [FIRFieldValue fieldValueForArrayRemove:@[@"east_coast"]] }];
Kotlin
Android
val washingtonRef = 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"))
Java
Android
DocumentReference washingtonRef = 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"));
Dart
final washingtonRef = 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"]), });
Java
Python
Python
(异步)
C++
// This is not yet supported.
Node.js
Go
// Not supported yet
PHP
PHP
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Unity
// This is not yet supported in the Unity SDK
C#
Ruby
// Not supported yet
递增数值
您可以递增或递减数字字段值,如以下示例所示。递增或递减操作会在字段的当前值基础上增加或减少给定数量。
Web 版本 9
import { doc, updateDoc, increment } from "firebase/firestore"; const washingtonRef = doc(db, "cities", "DC"); // Atomically increment the population of the city by 50. await updateDoc(washingtonRef, { population: increment(50) });
Web 版本 8
var washingtonRef = db.collection('cities').doc('DC'); // Atomically increment the population of the city by 50. washingtonRef.update({ population: firebase.firestore.FieldValue.increment(50) });
Swift
let washingtonRef = 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)) ])
Objective-C
FIRDocumentReference *washingtonRef = [[self.db collectionWithPath:@"cities"] documentWithPath:@"DC"]; // Atomically increment the population of the city by 50. // Note that increment() with no arguments increments by 1. [washingtonRef updateData:@{ @"population": [FIRFieldValue fieldValueForIntegerIncrement:50] }];
Kotlin
Android
val washingtonRef = db.collection("cities").document("DC") // Atomically increment the population of the city by 50. washingtonRef.update("population", FieldValue.increment(50))
Java
Android
DocumentReference washingtonRef = db.collection("cities").document("DC"); // Atomically increment the population of the city by 50. washingtonRef.update("population", FieldValue.increment(50));
Dart
var washingtonRef = db.collection('cities').doc('DC'); // Atomically increment the population of the city by 50. washingtonRef.update( {"population": FieldValue.increment(50)}, );
Java
Python
Python
(异步)
C++
// This is not yet supported.
Node.js
Go
PHP
PHP
如需向 Firestore 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
Unity
// This is not yet supported in the Unity SDK.
C#
Ruby
递增操作对于实现计数器非常有用。请注意,过快更新单个文档可能会导致争用或错误。如果您需要以非常高的速率更新计数器,请参阅分布式计数器页面。