programing

MongoDb 합계 쿼리

cafebook 2023. 3. 29. 21:53
반응형

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를 사용하는 경우의 예:

  1. 제품 가격의 총합을 계산합니다.
Products.aggregate([ { $match: {} }, { $group:
  { _id : null, sum : { $sum: "$Price" } }
}])
.then(res => console.log(res[0].sum));

({ $match: {} },제거할 수 있습니다.)


  1. 각 카테고리의 제품 가격 합계:
Products.aggregate([{ $group:
  { _id : '$Category', sum : { $sum: "$Price" } }
}])
.then(res => console.log(res));

언급URL : https://stackoverflow.com/questions/18969916/mongodb-sum-query

반응형