반응형
MongoDb 합계 쿼리
예를 들어 MongoDB에는 다음과 같은 데이터가 있습니다.
{ "_id" : ObjectId("524091f99c49c4c3f66b0e46"), "hour" : 10, "incoming", 100}
{ "_id" : ObjectId("5240a045dbeff33c7333aa51"), "hour" : 11, "incoming", 200}
{ "_id" : ObjectId("5240a2ecda0d37f35c618aca"), "hour" : 12, "incoming", 300}
이제 "SUM number in incoming number between 11~12"(결과 500)를 문의합니다만, Mongo Shell을 사용하여 어떻게 하면 됩니까?
Llovet이 제안했듯이, 통합 프레임워크가 바람직한 방법입니다.문의 내용은 다음과 같습니다.
db.CollectionNameGoesHere.aggregate({ $match: {
$and: [
{ hour: { $gte: 11 } },
{ hour: { $lte: 12 } }
]
} },
{ $group: { _id : null, sum : { $sum: "$incoming" } } });
파이프라인 끝에 $project 연산자를 추가하여 다음과 같이 결과 문서를 합계만 포함하도록 쉐이핑할 수도 있습니다.
{ $project: { _id: 0, sum: 1 } }
mongoose를 사용하는 경우의 예:
- 제품 가격의 총합을 계산합니다.
Products.aggregate([ { $match: {} }, { $group:
{ _id : null, sum : { $sum: "$Price" } }
}])
.then(res => console.log(res[0].sum));
({ $match: {} },
제거할 수 있습니다.)
- 각 카테고리의 제품 가격 합계:
Products.aggregate([{ $group:
{ _id : '$Category', sum : { $sum: "$Price" } }
}])
.then(res => console.log(res));
언급URL : https://stackoverflow.com/questions/18969916/mongodb-sum-query
반응형
'programing' 카테고리의 다른 글
리액트 훅: 사용 중인 첫 번째 실행 건너뛰기 효과 (0) | 2023.03.29 |
---|---|
Spring Boot 버전을 2.0.3에서 변경할 때 문제가 발생합니다.릴리스 2.1.0.빌드 스냅샷 (0) | 2023.03.29 |
TypeScript에서 Enum like type을 생성하는 방법 (0) | 2023.03.29 |
잭슨과의 JSON 역직렬화 커스텀 (0) | 2023.03.29 |
Woocommerce 숍 페이지 커스텀템플릿 (0) | 2023.03.29 |