프로젝트에서 사용자 정보, 사용자들이 추가하는 픽 등의 정보를 저장할 필요가 있었고, 이 데이터들을 Firestore에서 관리했다.
https://firebase.google.com/docs/firestore/query-data/get-data?hl=en
https://firebase.google.com/docs/firestore/query-data/order-limit-data?hl=en
기본적으로 get()
메서드로 문서를 가져올 수 있다. 아래는 cities의 SF 문서를 가져오는 것이다.
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)
}
get()
에 성공한다면 DocumentSnapShot
이 반환된다. DocumentSnapshot
은 Firestore에 있는 문서의 내용을 포함하고 있는 객체이다. 문서 안의 전체 데이터에 대해 알기 위해서는 documentSnapshot.data
를, 문서의 특정 필드 값을 알고 싶으면 documentSnapshot.data[필드명]
을 사용하면 된다. 만약 DocumentSnapshot
이 없는 문서를 가리키고 있다면 data
와 관련된 모든 값은 null이 반환된다.
문서를 쿼리하여 하나의 요청으로 여러 개의 문서를 가져올 수도 있다. where()
를 사용하여 특정 조건을 만족하는 모든 문서를 쿼리하고 get()
으로 가져올 수 있다. 아래는 cities 컬렉션의 문서 중 capital 필드가 true인 것만 가져오는 예제이다.
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)
}
이렇게 가져와진 쿼리를 만족하는 모든 문서는 문서 id 오름차순으로 결과가 반환된다. 이를 정렬하기 위해서는 orderBy()
를 사용하면 된다.
val citiesRef = db.collection("cities")
// cities 컬렉션에서 name 필드를 오름차순으로 정렬하여 첫 3개만 가져오기
citiesRef.orderBy("name").limit(3)
// cities 컬렉션에서 name 필드를 내림차순으로 정렬하여 첫 3개만 가져오기
citiesRef.orderBy("name", Query.Direction.DESCENDING).limit(3)
// state 기준으로 오름차순 정렬한 후 population 기준으로 내림차순 정렬하여 가져오기
citiesRef.orderBy("state").orderBy("population", Query.Direction.DESCENDING)
// population이 100000을 초과하는 문서를 population으로 오름차순 정렬하여 첫 2개만 가져오기
// 이상은 whereGreaterThanOrEqualTo()
citiesRef.whereGreaterThan("population", 100000).orderBy("population").limit(2)
담은 픽이나 등록한 픽을 가져올 때 최근 담은순/최근 등록순으로 가져오기 위해 orderBy()
를 사용했다.
문서 id를 지정하지 않으면 컬렉션의 모든 문서를 가져올 수 있다.