특정 기간의 데이터를 추출하여 포인트 합산을 하려고 한다. 주의할 점이라면 대상이 되는 데이터가 sub collection의 데이터이다.
이중 collection으로 user collection의 각 doc 마다 history collection이 있다.
- User collection
- id
- History collection
- id
- {type, subtype, point, rdt}
Firestore에서 인덱싱 설정을 해야 쿼리 데이터를 얻을 수 있다.
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));
}