- Produk
- Kasus Penggunaan
- Harga
-
Dokumen
- Ringkasan
- Dasar-dasar
- Build
- Rilis & Pantau
- Engage
- Referensi
- Sampel
- Komunitas
- Dukungan
- Buka konsol
Ada tiga cara untuk mengambil data yang tersimpan di Cloud Firestore. Salah satu dari metode ini dapat digunakan pada dokumen, koleksi dokumen, atau hasil kueri:
- Memanggil metode untuk mendapatkan data sekali.
- Menetapkan pemroses untuk menerima peristiwa perubahan data.
- Memuat data snapshot Firestore secara massal dari sumber eksternal melalui paket data. Lihat dokumen paket untuk mengetahui detailnya.
Saat Anda menetapkan pemroses, Cloud Firestore akan mengirim snapshot awal data ke pemroses, dan kemudian snapshot lain setiap kali dokumen berubah.
Data contoh
Untuk memulai, tulis beberapa data mengenai kota agar kita dapat melihat berbagai cara untuk membacanya kembali:
Catatan: Produk ini tidak tersedia di target watchOS dan App Clip. Catatan: Produk ini tidak tersedia di target watchOS dan App Clip. Web version 9
import { collection, doc, setDoc } from "firebase/firestore";
const citiesRef = collection(db, "cities");
await setDoc(doc(citiesRef, "SF"), {
name: "San Francisco", state: "CA", country: "USA",
capital: false, population: 860000,
regions: ["west_coast", "norcal"] });
await setDoc(doc(citiesRef, "LA"), {
name: "Los Angeles", state: "CA", country: "USA",
capital: false, population: 3900000,
regions: ["west_coast", "socal"] });
await setDoc(doc(citiesRef, "DC"), {
name: "Washington, D.C.", state: null, country: "USA",
capital: true, population: 680000,
regions: ["east_coast"] });
await setDoc(doc(citiesRef, "TOK"), {
name: "Tokyo", state: null, country: "Japan",
capital: true, population: 9000000,
regions: ["kanto", "honshu"] });
await setDoc(doc(citiesRef, "BJ"), {
name: "Beijing", state: null, country: "China",
capital: true, population: 21500000,
regions: ["jingjinji", "hebei"] });Web version 8
var citiesRef = db.collection("cities");
citiesRef.doc("SF").set({
name: "San Francisco", state: "CA", country: "USA",
capital: false, population: 860000,
regions: ["west_coast", "norcal"] });
citiesRef.doc("LA").set({
name: "Los Angeles", state: "CA", country: "USA",
capital: false, population: 3900000,
regions: ["west_coast", "socal"] });
citiesRef.doc("DC").set({
name: "Washington, D.C.", state: null, country: "USA",
capital: true, population: 680000,
regions: ["east_coast"] });
citiesRef.doc("TOK").set({
name: "Tokyo", state: null, country: "Japan",
capital: true, population: 9000000,
regions: ["kanto", "honshu"] });
citiesRef.doc("BJ").set({
name: "Beijing", state: null, country: "China",
capital: true, population: 21500000,
regions: ["jingjinji", "hebei"] });
Java
CollectionReference cities = db.collection("cities");
Map<String, Object> data1 = new HashMap<>();
data1.put("name", "San Francisco");
data1.put("state", "CA");
data1.put("country", "USA");
data1.put("capital", false);
data1.put("population", 860000);
data1.put("regions", Arrays.asList("west_coast", "norcal"));
cities.document("SF").set(data1);
Map<String, Object> data2 = new HashMap<>();
data2.put("name", "Los Angeles");
data2.put("state", "CA");
data2.put("country", "USA");
data2.put("capital", false);
data2.put("population", 3900000);
data2.put("regions", Arrays.asList("west_coast", "socal"));
cities.document("LA").set(data2);
Map<String, Object> data3 = new HashMap<>();
data3.put("name", "Washington D.C.");
data3.put("state", null);
data3.put("country", "USA");
data3.put("capital", true);
data3.put("population", 680000);
data3.put("regions", Arrays.asList("east_coast"));
cities.document("DC").set(data3);
Map<String, Object> data4 = new HashMap<>();
data4.put("name", "Tokyo");
data4.put("state", null);
data4.put("country", "Japan");
data4.put("capital", true);
data4.put("population", 9000000);
data4.put("regions", Arrays.asList("kanto", "honshu"));
cities.document("TOK").set(data4);
Map<String, Object> data5 = new HashMap<>();
data5.put("name", "Beijing");
data5.put("state", null);
data5.put("country", "China");
data5.put("capital", true);
data5.put("population", 21500000);
data5.put("regions", Arrays.asList("jingjinji", "hebei"));
cities.document("BJ").set(data5);Kotlin+KTX
val cities = db.collection("cities")
val data1 = hashMapOf(
"name" to "San Francisco",
"state" to "CA",
"country" to "USA",
"capital" to false,
"population" to 860000,
"regions" to listOf("west_coast", "norcal")
)
cities.document("SF").set(data1)
val data2 = hashMapOf(
"name" to "Los Angeles",
"state" to "CA",
"country" to "USA",
"capital" to false,
"population" to 3900000,
"regions" to listOf("west_coast", "socal")
)
cities.document("LA").set(data2)
val data3 = hashMapOf(
"name" to "Washington D.C.",
"state" to null,
"country" to "USA",
"capital" to true,
"population" to 680000,
"regions" to listOf("east_coast")
)
cities.document("DC").set(data3)
val data4 = hashMapOf(
"name" to "Tokyo",
"state" to null,
"country" to "Japan",
"capital" to true,
"population" to 9000000,
"regions" to listOf("kanto", "honshu")
)
cities.document("TOK").set(data4)
val data5 = hashMapOf(
"name" to "Beijing",
"state" to null,
"country" to "China",
"capital" to true,
"population" to 21500000,
"regions" to listOf("jingjinji", "hebei")
)
cities.document("BJ").set(data5)Dart
final cities = db.collection("cities");
final data1 = <String, dynamic>{
"name": "San Francisco",
"state": "CA",
"country": "USA",
"capital": false,
"population": 860000,
"regions": ["west_coast", "norcal"]
};
cities.doc("SF").set(data1);
final data2 = <String, dynamic>{
"name": "Los Angeles",
"state": "CA",
"country": "USA",
"capital": false,
"population": 3900000,
"regions": ["west_coast", "socal"],
};
cities.doc("LA").set(data2);
final data3 = <String, dynamic>{
"name": "Washington D.C.",
"state": null,
"country": "USA",
"capital": true,
"population": 680000,
"regions": ["east_coast"]
};
cities.doc("DC").set(data3);
final data4 = <String, dynamic>{
"name": "Tokyo",
"state": null,
"country": "Japan",
"capital": true,
"population": 9000000,
"regions": ["kanto", "honshu"]
};
cities.doc("TOK").set(data4);
final data5 = <String, dynamic>{
"name": "Beijing",
"state": null,
"country": "China",
"capital": true,
"population": 21500000,
"regions": ["jingjinji", "hebei"],
};
cities.doc("BJ").set(data5);Python
Mendapatkan dokumen
Contoh berikut menunjukkan cara mengambil konten dari sebuah dokumen menggunakan get():
Catatan: Produk ini tidak tersedia di target watchOS dan App Clip. Catatan: Produk ini tidak tersedia di target watchOS dan App Clip. Web version 9
import { doc, getDoc } from "firebase/firestore";
const docRef = doc(db, "cities", "SF");
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}Web version 8
var docRef = db.collection("cities").doc("SF");
docRef.get().then((doc) => {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch((error) => {
console.log("Error getting document:", error);
});Java
DocumentReference docRef = db.collection("cities").document("SF");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});Kotlin+KTX
val docRef = db.collection("cities").document("SF")
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
Log.d(TAG, "DocumentSnapshot data: ${document.data}")
} else {
Log.d(TAG, "No such document")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}Dart
final docRef = db.collection("cities").doc("SF");
docRef.get().then(
(DocumentSnapshot doc) {
final data = doc.data() as Map<String, dynamic>;
// ...
},
onError: (e) => print("Error getting document: $e"),
);Python
Opsi Sumber
Untuk platform dengan dukungan offline, Anda dapat menetapkan opsi source untuk mengontrol penggunaan cache offline oleh panggilan get.
Secara default, panggilan get akan mencoba mengambil snapshot dokumen terbaru dari database Anda. Pada platform dengan dukungan offline, library klien akan menggunakan cache offline jika jaringan tidak tersedia atau jika waktu permintaan habis.
Anda dapat menentukan opsi source dalam panggilan get() untuk mengubah perilaku default. Anda dapat mengambil hanya dari database dan mengabaikan cache offline, atau Anda dapat mengambil hanya dari cache offline. Contoh:
Catatan: Produk ini tidak tersedia di target watchOS dan App Clip. Catatan: Produk ini tidak tersedia di target watchOS dan App Clip. Tidak didukung di Java SDK. Web version 9
import { doc, getDocFromCache } from "firebase/firestore";
const docRef = doc(db, "cities", "SF");
// Get a document, forcing the SDK to fetch from the offline cache.
try {
const doc = await getDocFromCache(docRef);
// Document was found in the cache. If no cached document exists,
// an error will be returned to the 'catch' block below.
console.log("Cached document data:", doc.data());
} catch (e) {
console.log("Error getting cached document:", e);
}Web version 8
var docRef = db.collection("cities").doc("SF");
// Valid options for source are 'server', 'cache', or
// 'default'. See //firebase.google.com/docs/reference/js/firebase.firestore.GetOptions
// for more information.
var getOptions = {
source: 'cache'
};
// Get a document, forcing the SDK to fetch from the offline cache.
docRef.get(getOptions).then((doc) => {
// Document was found in the cache. If no cached document exists,
// an error will be returned to the 'catch' block below.
console.log("Cached document data:", doc.data());
}).catch((error) => {
console.log("Error getting cached document:", error);
});Java
DocumentReference docRef = db.collection("cities").document("SF");
// Source can be CACHE, SERVER, or DEFAULT.
Source source = Source.CACHE;
// Get the document, forcing the SDK to use the offline cache
docRef.get(source).addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
// Document found in the offline cache
DocumentSnapshot document = task.getResult();
Log.d(TAG, "Cached document data: " + document.getData());
} else {
Log.d(TAG, "Cached get failed: ", task.getException());
}
}
});Kotlin+KTX
val docRef = db.collection("cities").document("SF")
// Source can be CACHE, SERVER, or DEFAULT.
val source = Source.CACHE
// Get the document, forcing the SDK to use the offline cache
docRef.get(source).addOnCompleteListener { task ->
if (task.isSuccessful) {
// Document found in the offline cache
val document = task.result
Log.d(TAG, "Cached document data: ${document?.data}")
} else {
Log.d(TAG, "Cached get failed: ", task.exception)
}
}Dart
final docRef = db.collection("cities").doc("SF");
// Source can be CACHE, SERVER, or DEFAULT.
const source = Source.cache;
docRef.get(const GetOptions(source: source)).then(
(res) => print("Successfully completed"),
onError: (e) => print("Error completing: $e"),
);
Tidak didukung di Python SDK.
Tidak didukung di Node.js SDK.
Tidak didukung di Go SDK.
Tidak didukung di PHP SDK.
Tidak didukung di Unity SDK.
Tidak didukung di C# SDK.
Tidak didukung di Ruby SDK.
Objek kustom
Contoh sebelumnya mengambil konten dokumen sebagai peta, tetapi dalam beberapa bahasa akan lebih mudah untuk menggunakan jenis objek kustom. Di bagian Menambahkan Data, Anda menentukan class City yang digunakan untuk menentukan setiap kota. Anda dapat mengembalikan dokumen menjadi objek City:
Untuk menggunakan objek kustom, Anda harus menentukan fungsi FirestoreDataConverter untuk class Anda. Contoh: Untuk menggunakan objek kustom, Anda
harus menentukan fungsi FirestoreDataConverter untuk class Anda. Contoh: Panggil pengonversi data dengan operasi baca Anda. Setelah konversi, Anda dapat mengakses metode objek kustom: Panggil pengonversi data dengan operasi baca Anda. Setelah konversi, Anda dapat mengakses metode objek kustom: Catatan: Produk ini tidak
tersedia di target watchOS dan App Clip. Untuk mendukung serialisasi jenis otomatis di Swift, jenisnya harus sesuai dengan protokol Codable, dan Anda harus menyertakan pod 'FirebaseFirestoreSwift' sebagai dependensi project Anda. Catatan: Produk ini tidak tersedia di target watchOS dan App Clip. Dalam Objective-C,
Anda harus melakukannya secara manual. Web version 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 version 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);
}
};Web version 9
import { doc, getDoc} from "firebase/firestore";
const ref = doc(db, "cities", "LA").withConverter(cityConverter);
const docSnap = await getDoc(ref);
if (docSnap.exists()) {
// Convert to City object
const city = docSnap.data();
// Use a City instance method
console.log(city.toString());
} else {
console.log("No such document!");
}Web version 8
db.collection("cities").doc("LA")
.withConverter(cityConverter)
.get().then((doc) => {
if (doc.exists){
// Convert to City object
var city = doc.data();
// Use a City instance method
console.log(city.toString());
} else {
console.log("No such document!");
}}).catch((error) => {
console.log("Error getting document:", error);
});
Java
Penting: Setiap class kustom harus memiliki konstruktor publik yang tidak membutuhkan argumen. Selain itu, class tersebut harus menyertakan pengambil publik untuk setiap properti.
DocumentReference docRef = db.collection("cities").document("BJ"); docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { City city = documentSnapshot.toObject(City.class); } });Kotlin+KTX
val docRef = db.collection("cities").document("BJ") docRef.get().addOnSuccessListener { documentSnapshot -> val city = documentSnapshot.toObject<City>() }Dart
Untuk menggunakan objek kustom, Anda harus menentukan fungsi konversi data Firestore untuk class Anda. Contoh:
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, }; } }Kemudian, buat referensi dokumen dengan fungsi konversi data Anda. Setiap operasi baca yang Anda lakukan menggunakan referensi ini akan menampilkan instance class kustom Anda:
final ref = db.collection("cities").doc("LA").withConverter( fromFirestore: City.fromFirestore, toFirestore: (City city, _) => city.toFirestore(), ); final docSnap = await ref.get(); final city = docSnap.data(); // Convert to City object if (city != null) { print(city); } else { print("No such document."); }Setiap class kustom harus memiliki konstruktor publik yang tidak membutuhkan argumen. Selain itu, class tersebut harus menyertakan pengambil publik untuk setiap properti.
Python
Node.js menggunakan objek JavaScript.
Tidak berlaku untuk PHP.
Tidak berlaku untuk Ruby.
Mendapatkan beberapa dokumen dari koleksi
Anda juga dapat mengambil beberapa dokumen dengan satu permintaan, dengan membuat kueri terhadap dokumen dalam koleksi. Misalnya, Anda dapat menggunakan where() guna membuat kueri untuk semua dokumen yang memenuhi kondisi tertentu, kemudian menggunakan get() untuk mengambil hasilnya:
Catatan: Produk ini tidak tersedia di target watchOS dan App Clip. Catatan: Produk ini tidak tersedia di target watchOS dan App Clip. Web version 9
import { collection, query, where, getDocs } from "firebase/firestore";
const q = query(collection(db, "cities"), where("capital", "==", true));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});Web version 8
db.collection("cities").where("capital", "==", true)
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
})
.catch((error) => {
console.log("Error getting documents: ", error);
});Java
db.collection("cities")
.whereEqualTo("capital", true)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});Kotlin+KTX
db.collection("cities")
.whereEqualTo("capital", true)
.get()
.addOnSuccessListener { documents ->
for (document in documents) {
Log.d(TAG, "${document.id} => ${document.data}")
}
}
.addOnFailureListener { exception ->
Log.w(TAG, "Error getting documents: ", exception)
}Dart
db.collection("cities").where("capital", isEqualTo: true).get().then(
(res) => print("Successfully completed"),
onError: (e) => print("Error completing: $e"),
);Python
Secara default, Cloud Firestore mengambil semua dokumen yang memenuhi kueri dalam urutan menaik menurut ID dokumen, tetapi Anda dapat mengurutkan dan membatasi data yang ditampilkan.
Mendapatkan semua dokumen dalam koleksi
Selain itu, Anda dapat mengambil semua dokumen dalam koleksi dengan menghilangkan filter where() sepenuhnya:
Catatan: Produk ini tidak tersedia di target watchOS dan App Clip. Catatan:
Produk ini tidak tersedia di target watchOS dan App Clip. Web version 9
import { collection, getDocs } from "firebase/firestore";
const querySnapshot = await getDocs(collection(db, "cities"));
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});Web version 8
db.collection("cities").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
});Java
db.collection("cities")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});Kotlin+KTX
db.collection("cities")
.get()
.addOnSuccessListener { result ->
for (document in result) {
Log.d(TAG, "${document.id} => ${document.data}")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "Error getting documents: ", exception)
}Dart
db.collection("cities").get().then(
(res) => print("Successfully completed"),
onError: (e) => print("Error completing: $e"),
);Python
Mendapatkan beberapa dokumen dari sebuah grup koleksi
Grup koleksi terdiri dari semua koleksi dengan ID yang sama. Misalnya, jika setiap dokumen dalam koleksi cities memiliki subkoleksi yang disebut landmarks, semua subkoleksi landmarks akan tergabung dalam grup koleksi yang sama. Secara default, kueri mengambil hasil dari satu koleksi di database Anda. Gunakan kueri grup koleksi untuk mengambil hasil dari grup koleksi, bukan dari satu koleksi.
Menampilkan daftar subkoleksi dokumen
Metode library klien server Cloud Firestore listCollections() menampilkan daftar semua subkoleksi referensi dokumen.
Pengambilan daftar koleksi tidak dapat dilakukan dengan library klien seluler/web. Anda sebaiknya hanya mencari nama koleksi sebagai bagian dari tugas administratif di lingkungan server yang tepercaya. Jika ternyata Anda memerlukan kemampuan ini pada library klien seluler/web, sebaiknya buat ulang struktur data Anda sehingga nama subkoleksi mudah diprediksi.
Tidak tersedia di library klien Web. Tidak tersedia di library klien Swift. Tidak tersedia di library klien Objective-C. Tidak tersedia di library klien Android. Tidak tersedia di library klien Android. Tidak tersedia di library klien Flutter. Tidak tersedia di library klien C++. Java
Kotlin+KTX
Dart
Python
Pelajari berbagai jenis kueri lebih lanjut.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2022-10-15 UTC.
[{ "type": "thumb-down", "id": "missingTheInformationINeed", "label":"Informasi yang saya butuhkan tidak ada" },{ "type": "thumb-down", "id": "tooComplicatedTooManySteps", "label":"Terlalu rumit/langkahnya terlalu banyak" },{ "type": "thumb-down", "id": "outOfDate", "label":"Sudah usang" },{ "type": "thumb-down", "id": "translationIssue", "label":"Masalah terjemahan" },{ "type": "thumb-down", "id": "samplesCodeIssue", "label":"Masalah kode / contoh" },{ "type": "thumb-down", "id": "otherDown", "label":"Lainnya" }] [{ "type": "thumb-up", "id": "easyToUnderstand", "label":"Mudah dipahami" },{ "type": "thumb-up", "id": "solvedMyProblem", "label":"Memecahkan masalah saya" },{ "type": "thumb-up", "id": "otherUp", "label":"Lainnya" }]