1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Firebase Cloud Firestore覚え書き Kotlin

Last updated at Posted at 2020-11-26

ドキュメントへの参照

単一の場合はDocumentReference
複数の場合はCollectionReferenceまたはQuery

ドキュメントの取得

get()関数を使用してドキュメントを取得する。

Snapshotって何?

取得された中身。

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

1回のリクエストで複数のドキュメントを取得する。
where()を使用することで、特定の条件を満たすすべてのドキュメントを取得できる。(一般的なRDB的な使い方)
取得される順番はドキュメントIDの昇順。

db.collection("cities")
        .whereEqualTo("capital", true)    // whereフィルター
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents) {
                Log.d(TAG, "${document.id} => ${document.data}")
            }
        }
        .addOnFailureListener { exception ->
            Log.w(TAG, "Error getting documents: ", exception)
        }

サブコレクションの取得

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

クエリの制限

ORは使用不可

OR条件ごとに独立したクエリを作成し、アプリでクエリ結果を結合する必要がある。

!=は使用不可

whereGreaterThanwhereLessThanを結合することで、同じ結果をセットする。

複数のフィールドの範囲フィルタは不可

有効な例

citiesRef.whereGreaterThanOrEqualTo("state", "CA")
        .whereLessThanOrEqualTo("state", "IN")
citiesRef.whereEqualTo("state", "CA")
        .whereGreaterThan("population", 1000000)

無効な例

citiesRef.whereGreaterThanOrEqualTo("state", "CA")
        .whereGreaterThan("population", 100000)

取得した値をリスト形式で表示させるために

関数を使用して、getした値をmapで渡す。

    suspend fun getList(): List<String?> {
        val response = db.collection("user")
            .get()
            .await()
        return response.documents.map { it.getString("name") }
    }

データのあるなしは確認する

データの有無に関わらず、Snapshotは返ってくるので、データがあるかどうかの確認はする。

ドキュメントを作成し、サブコレクション作成後フィールドを追加する

db.collection("teams")
  .document()
  .collection("users")
  .add(User(10, "hoge"))
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?