Javascript Query by Firefoo

He SEO·2022년 5월 26일

쿼리의 목적

특정 기간의 데이터를 추출하여 포인트 합산을 하려고 한다. 주의할 점이라면 대상이 되는 데이터가 sub collection의 데이터이다.

Collection 구조

이중 collection으로 user collection의 각 doc 마다 history collection이 있다.

- User collection 
	 - id 
    	- History collection 
        	- id
            	- {type, subtype, point, rdt}

조건

  • startDate ~ endDate
  • type = 1
  • subtype = 2

Indexing collectionGroup

Firestore에서 인덱싱 설정을 해야 쿼리 데이터를 얻을 수 있다.

  • type 오름차순, subtype 오름차순, rdt 내림차순
  • Collection Group 선택 후 생성

Query

const minDate = new Date("2022-05-01T00:00:00");
const maxDate = new Date("2022-05-31T00:00:00");

const minTimestamp = admin.firestore.Timestamp.fromDate(minDate)
const maxTimestamp = admin.firestore.Timestamp.fromDate(maxDate)

async function run() {
const query = await db.collectionGroup("history")
  .where("type", "==", 1)
  .where("subtype", "==", 2)
  .where("rdt", ">=", minTimestamp)
  .where("rdt", "<", maxTimestamp)
  .get();
  
  const points = query.docs.map((doc) => doc.data().point);
  console.log("sum : " + _.sum(points));
}

참고 사이트

profile
BACKEND 개발 기록 중. 감사합니다 😘

0개의 댓글