2017-10-03 11 views
5

firestore라는 새로운 firebase 데이터베이스를 사용하여 컬렉션에있는 아이템 수를 계산할 수 있습니까?Firebase firestore collection count

그렇다면 어떻게 관리 할 수 ​​있습니까?

+6

[Cloud Firestore로 컬렉션의 문서 수를 계산하는 방법] (https://stackoverflow.com/questions/46553314/how-to -get-a-collection-of-a-collection-of-a-collection-of-cloud-firestore) –

답변

0

내가 아는 한 지금까지는 빌드 인 솔루션이없고 노드 sdk에서만 가능합니다. 당신은 당신이 선택하고자하는 필드 정의

ALL 기타 사항 서보 -OFF ([필드])

을 사용할 수 있습니다

db.collection ('someCollection을')가있는 경우. 비어있는 select()를 수행하면 일련의 문서 참조를 얻을 수 있습니다.

예 :

db.collection('someCollection').select().get().then( (snapshot) => console.log(snapshot.docs.length) );

이 솔루션은 경우에만 모든 문서를 다운로드 및 대형 컬렉션에 확장되지 않는 최악의 경우에 대한 최적화!

는 또한 이것 좀 있습니다
How to get a count of number of documents in a collection with Cloud Firestore

1

없음을, 어떤 내장 집계 쿼리에 대한 지원이 지금은 없습니다. 그러나 당신이 할 수있는 몇 가지 일이 있습니다.

첫 번째는 documented here입니다. 트랜잭션 또는 클라우드 기능을 사용하여 집계 정보를 유지 관리 할 수 ​​있습니다.

이 예에서는 함수를 사용하여 평균값뿐만 아니라 하위 수집의 등급 수를 추적하는 방법을 보여줍니다.

exports.aggregateRatings = firestore 
    .document('restaurants/{restId}/ratings/{ratingId}') 
    .onWrite(event => { 
    // Get value of the newly added rating 
    var ratingVal = event.data.get('rating'); 

    // Get a reference to the restaurant 
    var restRef = db.collection('restaurants').document(event.params.restId); 

    // Update aggregations in a transaction 
    return db.transaction(transaction => { 
     return transaction.get(restRef).then(restDoc => { 
     // Compute new number of ratings 
     var newNumRatings = restDoc.data('numRatings') + 1; 

     // Compute new average rating 
     var oldRatingTotal = restDoc.data('avgRating') * restDoc.data('numRatings'); 
     var newAvgRating = (oldRatingTotal + ratingVal)/newNumRatings; 

     // Update restaurant info 
     return transaction.update(restRef, { 
      avgRating: newAvgRating, 
      numRatings: newNumRatings 
     }); 
     }); 
    }); 
}); 

jbb에서 언급 한 솔루션은 자주 문서를 자주 집계하지 않으려는 경우에도 유용합니다. select() 문을 사용하여 각 문서를 모두 다운로드하지 않도록하십시오. 이는 카운트가 필요할 때 많은 대역폭을 필요로합니다. select()은 현재 서버 SDK에서만 사용할 수 있으므로 모바일 앱에서 솔루션이 작동하지 않습니다.

3

이렇게하는 가장 간단한 방법은 "querySnapshot"의 크기를 읽는 것입니다.

db.collection("cities").get().then(function(querySnapshot) {  
    console.log(querySnapshot.size); 
}); 

"querySnapshot"내에있는 문서 배열의 길이를 읽을 수도 있습니다.

querySnapshot.docs.length; 

또는 "querySnapshot"이 비어있는 값을 읽으면 비어있는 값을 반환합니다.

querySnapshot.empty; 
+3

각 문서의 읽기에는 "비용이 드는"것을 유의하십시오.따라서 컬렉션에서 100 개 항목을이 방법으로 계산하면 100 회의 읽기가 청구됩니다. – Georg

+0

정확하지만 컬렉션의 문서 수를 합산하는 다른 방법은 없습니다. 그리고 이미 콜렉션을 가져온 경우 "docs"배열을 읽는 것이 더 이상 인출 할 필요가 없으므로 더 많은 판독 값을 "부담하지"않습니다. – Ompel

+0

이것은 메모리에있는 모든 문서를 읽습니다! 큰 데이터 세트를 위해 행운을 빈다. –