Cloud Firestore でデータを取得する

Cloud Firestore に格納されているデータを取得するには 2 つの方法があります。これらの方法のいずれかを、ドキュメント、ドキュメントのコレクション、クエリの結果に対して使用することができます。

  • メソッドを呼び出してデータを取得する。
  • データ変更イベントを受信するリスナーを設定する。

リスナーを設定すると、Cloud Firestore からリスナーにデータの初期スナップショットが送信され、その後ドキュメントが変更されるたびに新たなスナップショットが送信されます。

データの例

まず始めに、都市に関するデータを書き込み、データを読み戻すさまざまな方法を確認します。

ウェブ
var citiesRef = db.collection("cities");

citiesRef.doc("SF").set({
    name: "San Francisco", state: "CA", country: "USA",
    capital: false, population: 860000 });
citiesRef.doc("LA").set({
    name: "Los Angeles", state: "CA", country: "USA",
    capital: false, population: 3900000 });
citiesRef.doc("DC").set({
    name: "Washington, D.C.", state: null, country: "USA",
    capital: true, population: 680000 });
citiesRef.doc("TOK").set({
    name: "Tokyo", state: null, country: "Japan",
    capital: true, population: 9000000 });
citiesRef.doc("BJ").set({
    name: "Beijing", state: null, country: "China",
    capital: true, population: 21500000 });
Swift
let citiesRef = db.collection("cities")

citiesRef.document("SF").setData([
    "name": "San Francisco",
    "state": "CA",
    "country": "USA",
    "capital": false,
    "population": 860000
    ])
citiesRef.document("LA").setData([
    "name": "Los Angeles",
    "state": "CA",
    "country": "USA",
    "capital": false,
    "population": 3900000
    ])
citiesRef.document("DC").setData([
    "name": "Washington D.C.",
    "country": "USA",
    "capital": true,
    "population": 680000
    ])
citiesRef.document("TOK").setData([
    "name": "Tokyo",
    "country": "Japan",
    "capital": true,
    "population": 9000000
    ])
citiesRef.document("BJ").setData([
    "name": "Beijing",
    "country": "China",
    "capital": true,
    "population": 21500000
    ])
Objective-C
FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"];
[[citiesRef documentWithPath:@"SF"] setData:@{
  @"name": @"San Francisco",
  @"state": @"CA",
  @"country": @"USA",
  @"capital": @(NO),
  @"population": @860000
}];
[[citiesRef documentWithPath:@"LA"] setData:@{
  @"name": @"Los Angeles",
  @"state": @"CA",
  @"country": @"USA",
  @"capital": @(NO),
  @"population": @3900000
}];
[[citiesRef documentWithPath:@"DC"] setData:@{
  @"name": @"Washington D.C.",
  @"country": @"USA",
  @"capital": @(YES),
  @"population": @680000
}];
[[citiesRef documentWithPath:@"TOK"] setData:@{
  @"name": @"Tokyo",
  @"country": @"Japan",
  @"capital": @(YES),
  @"population": @9000000
}];
[[citiesRef documentWithPath:@"BJ"] setData:@{
  @"name": @"Beijing",
  @"country": @"China",
  @"capital": @(YES),
  @"population": @21500000
}];
  
Android
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);
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);
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);
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);
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);
cities.document("BJ").set(data5);
Java
CollectionReference cities = db.collection("cities");
List<ApiFuture<WriteResult>> futures = new ArrayList<>();
futures.add(cities.document("SF").set(new City("San Francisco", "CA", "USA", false, 860000L)));
futures.add(cities.document("LA").set(new City("Los Angeles", "CA", "USA", false, 3900000L)));
futures.add(cities.document("DC").set(new City("Washington D.C.", null, "USA", true, 680000L)));
futures.add(cities.document("TOK").set(new City("Tokyo", null, "Japan", true, 9000000L)));
futures.add(cities.document("BJ").set(new City("Beijing", null, "China", true, 21500000L)));
// (optional) block on operation
ApiFutures.allAsList(futures).get();
Python
class City(object):
    def __init__(self, name, state, country, capital=False, population=0):
        self.name = name
        self.state = state
        self.country = country
        self.capital = capital
        self.population = population

    @staticmethod
    def from_dict(source):
        # ...

    def to_dict(self):
        # ...

    def __repr__(self):
        return u'City(name={}, country={}, population={}, capital={})'.format(
            self.name, self.country, self.population, self.capital)

cities_ref = db.collection(u'cities')
cities_ref.document(u'SF').set(
    City(u'San Francisco', u'CA', u'USA', False, 860000).to_dict())
cities_ref.document(u'LA').set(
    City(u'Los Angeles', u'CA', u'USA', False, 3900000).to_dict())
cities_ref.document(u'DC').set(
    City(u'Washington D.C.', None, u'USA', True, 680000).to_dict())
cities_ref.document(u'TOK').set(
    City(u'Tokyo', None, u'Japan', True, 9000000).to_dict())
cities_ref.document(u'BJ').set(
    City(u'Beijing', None, u'China', True, 21500000).to_dict())
Node.js
var citiesRef = db.collection('cities');

var setSf = citiesRef.doc('SF').set({
    name: 'San Francisco', state: 'CA', country: 'USA',
    capital: false, population: 860000 });
var setLa = citiesRef.doc('LA').set({
    name: 'Los Angeles', state: 'CA', country: 'USA',
    capital: false, population: 3900000 });
var setDc = citiesRef.doc('DC').set({
    name: 'Washington, D.C.', state: null, country: 'USA',
    capital: true, population: 680000 });
var setTok = citiesRef.doc('TOK').set({
    name: 'Tokyo', state: null, country: 'Japan',
    capital: true, population: 9000000 });
var setBj = citiesRef.doc('BJ').set({
    name: 'Beijing', state: null, country: 'China',
    capital: true, population: 21500000 });
Go
cities := []struct {
	id string
	c  City
}{
	{id: "SF", c: City{Name: "San Francisco", State: "CA", Country: "USA", Capital: false, Population: 860000}},
	{id: "LA", c: City{Name: "Los Angeles", State: "CA", Country: "USA", Capital: false, Population: 3900000}},
	{id: "DC", c: City{Name: "Washington D.C.", Country: "USA", Capital: false, Population: 680000}},
	{id: "TOK", c: City{Name: "Tokyo", Country: "Japan", Capital: true, Population: 9000000}},
	{id: "BJ", c: City{Name: "Beijing", Country: "China", Capital: true, Population: 21500000}},
}
for _, c := range cities {
	_, err := client.Collection("cities").Doc(c.id).Set(ctx, c.c)
	if err != nil {
		return err
	}
}
PHP
$citiesRef = $db->collection('cities');
$citiesRef->document('SF')->set([
    'name' => 'San Francisco',
    'state' => 'CA',
    'country' => 'USA',
    'capital' => false,
    'population' => 860000
]);
$citiesRef->document('LA')->set([
    'name' => 'Los Angeles',
    'state' => 'CA',
    'country' => 'USA',
    'capital' => false,
    'population' => 3900000
]);
$citiesRef->document('DC')->set([
    'name' => 'Washington D.C.',
    'state' => null,
    'country' => 'USA',
    'capital' => true,
    'population' => 680000
]);
$citiesRef->document('TOK')->set([
    'name' => 'Tokyo',
    'state' => null,
    'country' => 'Japan',
    'capital' => true,
    'population' => 9000000
]);
$citiesRef->document('BJ')->set([
    'name' => 'Beijing',
    'state' => null,
    'country' => 'China',
    'capital' => true,
    'population' => 21500000
]);
printf('Added example cities data to the cities collection.' . PHP_EOL);

ドキュメントを取得する

次の例は、get() を使用して単一のドキュメントの内容を取得する方法を示しています。

ウェブ
var docRef = db.collection("cities").doc("SF");

docRef.get().then(function(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(function(error) {
    console.log("Error getting document:", error);
});
Swift
let docRef = db.collection("cities").document("SF")

docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
        print("Document data: \(dataDescription)")
    } else {
        print("Document does not exist")
    }
}
Objective-C
FIRDocumentReference *docRef =
    [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"];
[docRef getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  if (snapshot.exists) {
    // Document data may be nil if the document exists but has no keys or values.
    NSLog(@"Document data: %@", snapshot.data);
  } else {
    NSLog(@"Document does not exist");
  }
}];
  
Android
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());
        }
    }
});
Java
DocumentReference docRef = db.collection("cities").document("SF");
// asynchronously retrieve the document
ApiFuture<DocumentSnapshot> future = docRef.get();
// ...
// future.get() blocks on response
DocumentSnapshot document = future.get();
if (document.exists()) {
  System.out.println("Document data: " + document.getData());
} else {
  System.out.println("No such document!");
}
Python
doc_ref = db.collection(u'cities').document(u'SF')

try:
    doc = doc_ref.get()
    print(u'Document data: {}'.format(doc.to_dict()))
except google.cloud.exceptions.NotFound:
    print(u'No such document!')
Node.js
var cityRef = db.collection('cities').doc('SF');
var getDoc = cityRef.get()
    .then(doc => {
      if (!doc.exists) {
        console.log('No such document!');
      } else {
        console.log('Document data:', doc.data());
      }
    })
    .catch(err => {
      console.log('Error getting document', err);
    });
Go
dsnap, err := client.Collection("cities").Doc("SF").Get(ctx)
if err != nil {
	return nil, err
}
m := dsnap.Data()
fmt.Printf("Document data: %#v\n", m)
PHP
$docRef = $db->collection('cities')->document('SF');
$snapshot = $docRef->snapshot();

if ($snapshot->exists()) {
    printf('Document data:' . PHP_EOL);
    print_r($snapshot->fields());
} else {
    printf('Document %s does not exist!' . PHP_EOL, $snapshot->id());
}

カスタム オブジェクト

前の例では、ドキュメントの内容をマップとして取得しましたが、一部の言語では多くの場合、カスタムのオブジェクト タイプを使用する方が便利です。データを追加するセクションでは、City クラスを定義し、それを使用して各都市を定義しました。次の方法で、ドキュメントを City オブジェクトに戻すことができます。

ウェブ
  // Web uses JavaScript objects
  
Swift
let docRef = db.collection("cities").document("BJ")

docRef.getDocument { (document, error) in
    if let city = document.flatMap({
      $0.data().flatMap({ (data) in
        return City(dictionary: data)
      })
    }) {
        print("City: \(city)")
    } else {
        print("Document does not exist")
    }
}
  
Objective-C
FIRDocumentReference *docRef =
[[self.db collectionWithPath:@"cities"] documentWithPath:@"BJ"];
[docRef getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  FSTCity *city = [[FSTCity alloc] initWithDictionary:snapshot.data];
  if (city != nil) {
    NSLog(@"City: %@", city);
  } else {
    NSLog(@"Document does not exist");
  }
}];
  
Android
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);
    }
});
  
Java
DocumentReference docRef = db.collection("cities").document("BJ");
// asynchronously retrieve the document
ApiFuture<DocumentSnapshot> future = docRef.get();
// block on response
DocumentSnapshot document = future.get();
City city = null;
if (document.exists()) {
  // convert document to POJO
  city = document.toObject(City.class);
  System.out.println(city);
} else {
  System.out.println("No such document!");
}
Python
doc_ref = db.collection(u'cities').document(u'BJ')

doc = doc_ref.get()
city = City.from_dict(doc.to_dict())
print(city)
Node.js
// Node.js uses JavaScript objects
Go
dsnap, err := client.Collection("cities").Doc("BJ").Get(ctx)
if err != nil {
	return nil, err
}
var c City
dsnap.DataTo(&c)
fmt.Printf("Document data: %#v\n", c)
PHP
// Not applicable for PHP

コレクションから複数のドキュメントを取得する

コレクション内のドキュメントに対してクエリを実行すれば、1 回のリクエストで複数のドキュメントを取得することも可能です。たとえば where() を使用して、特定の条件を満たすすべてのドキュメントをクエリし、get() を使用して結果を取得することができます。

ウェブ
db.collection("cities").where("capital", "==", true)
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });
Swift
db.collection("cities").whereField("capital", isEqualTo: true)
    .getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
            }
        }
}
Objective-C
[[[self.db collectionWithPath:@"cities"] queryWhereField:@"capital" isEqualTo:@(YES)]
    getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) {
      if (error != nil) {
        NSLog(@"Error getting documents: %@", error);
      } else {
        for (FIRDocumentSnapshot *document in snapshot.documents) {
          NSLog(@"%@ => %@", document.documentID, document.data);
        }
      }
    }];
  
Android
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());
                }
            }
        });
Java
//asynchronously retrieve multiple documents
ApiFuture<QuerySnapshot> future =
    db.collection("cities").whereEqualTo("capital", true).get();
// future.get() blocks on response
List<QueryDocumentSnapshot> documents = future.get().getDocuments();
for (DocumentSnapshot document : documents) {
  System.out.println(document.getId() + " => " + document.toObject(City.class));
}
Python
docs = db.collection(u'cities').where(u'capital', u'==', True).get()

for doc in docs:
    print(u'{} => {}'.format(doc.id, doc.to_dict()))
Node.js
var citiesRef = db.collection('cities');
var query = citiesRef.where('capital', '==', true).get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        console.log(doc.id, '=>', doc.data());
      });
    })
    .catch(err => {
      console.log('Error getting documents', err);
    });
Go
fmt.Println("All capital cities:")
iter := client.Collection("cities").Where("capital", "==", true).Documents(ctx)
for {
	doc, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return err
	}
	fmt.Println(doc.Data())
}
PHP
$citiesRef = $db->collection('cities');
$query = $citiesRef->where('capital', '=', true);
$documents = $query->documents();
foreach ($documents as $document) {
    if ($document->exists()) {
        printf('Document data for document %s:' . PHP_EOL, $document->id());
        print_r($document->fields());
        printf(PHP_EOL);
    } else {
        printf('Document %s does not exist!' . PHP_EOL, $snapshot->id());
    }
}

コレクションのすべてのドキュメントを取得する

where() フィルタを全体的に省略することによって、コレクション内のすべてのドキュメントを取得することもできます。

ウェブ
db.collection("cities").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });
});
Swift
db.collection("cities").getDocuments() { (querySnapshot, err) in
    if let err = err {
        print("Error getting documents: \(err)")
    } else {
        for document in querySnapshot!.documents {
            print("\(document.documentID) => \(document.data())")
        }
    }
}
Objective-C
[[self.db collectionWithPath:@"cities"]
    getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) {
      if (error != nil) {
        NSLog(@"Error getting documents: %@", error);
      } else {
        for (FIRDocumentSnapshot *document in snapshot.documents) {
          NSLog(@"%@ => %@", document.documentID, document.data);
        }
      }
    }];
  
Android
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());
                }
            }
        });
Java
//asynchronously retrieve all documents
ApiFuture<QuerySnapshot> future = db.collection("cities").get();
// future.get() blocks on response
List<QueryDocumentSnapshot> documents = future.get().getDocuments();
for (QueryDocumentSnapshot document : documents) {
  System.out.println(document.getId() + " => " + document.toObject(City.class));
}
Python
docs = db.collection(u'cities').get()

for doc in docs:
    print(u'{} => {}'.format(doc.id, doc.to_dict()))
Node.js
var citiesRef = db.collection('cities');
var allCities = citiesRef.get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        console.log(doc.id, '=>', doc.data());
      });
    })
    .catch(err => {
      console.log('Error getting documents', err);
    });
Go
fmt.Println("All cities:")
iter := client.Collection("cities").Documents(ctx)
for {
	doc, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return err
	}
	fmt.Println(doc.Data())
}
PHP
$citiesRef = $db->collection('cities');
$documents = $citiesRef->documents();
foreach ($documents as $document) {
    if ($document->exists()) {
        printf('Document data for document %s:' . PHP_EOL, $document->id());
        print_r($document->fields());
        printf(PHP_EOL);
    } else {
        printf('Document %s does not exist!' . PHP_EOL, $snapshot->id());
    }
}

ドキュメントのサブコレクションの一覧を取得する

Cloud Firestore サーバーのクライアント ライブラリの getCollections() メソッドを使用すると、ドキュメント参照のすべてのサブコレクションの一覧を取得できます。

コレクションの一覧は、モバイル / ウェブ クライアントのライブラリを使用して取得することはできません。コレクション名の検索は、必ず信頼できるサーバー環境で管理タスクの一部として実行する必要があります。この機能がモバイル / ウェブ クライアントのライブラリで必要になると思われる場合は、サブコレクション名が予測可能になるようにデータを再構築することを検討してください。

ウェブ
// Not available in the Web client library.
Swift
// Not available in the iOS client library.
Objective-C
// Not available in the Objective-C client library.
  
Android
// Not available in the Android client library.
Java
Iterable<CollectionReference> collections =
    db.collection("cities").document("SF").getCollections();

for (CollectionReference collRef : collections) {
  System.out.println("Found subcollection with id: " + collRef.getId());
}
Python
// Not available in the Python client library
Node.js
var sfRef = db.collection('cities').doc('SF');
sfRef.getCollections().then(collections => {
  collections.forEach(collection => {
    console.log('Found subcollection with id:', collection.id);
  });
});
Go
iter := client.Collection("cities").Doc("SF").Collections(ctx)
for {
	collRef, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return err
	}
	fmt.Printf("Found collection with id: %s\n", collRef.ID)
}
PHP
$cityRef = $db->collection('cities')->document('SF');
$collections = $cityRef->collections();
foreach ($collections as $collection) {
    printf('Found subcollection with id: %s' . PHP_EOL, $collection->id());
}

詳細については、さまざまな種類のクエリをご覧ください。

フィードバックを送信...

ご不明な点がありましたら、Google のサポートページをご覧ください。